假设我有这样的字符串:
PH&N 2015 LifeTime Series D
PH&N 2020 LifeTime Series D
PH&N 2025 LifeTime Series D
PH&N 2030 LifeTime Series D
PH&N 2035 LifeTime Series D
PH&N 2040 LifeTime Series D
PH&N 2045 LifeTime Series D
如何使用R:
将数字移动到最后PH&N LifeTime Series D 2015
PH&N LifeTime Series D 2020
PH&N LifeTime Series D 2025
... and so on
使用gsub()的解决方案更可取。
答案 0 :(得分:4)
gsub("([[:alpha:]]+\\s)([[:digit:]]+)\\s(.+)", "\\1\\3 \\2", dat2$V1)
[1]“PH& N LifeTime Series D2015”“PH& N LifeTime Series D2020”“PH& N LifeTime Series D2025”“PH& N LifeTime Series D2030”“PH& N LifeTime Series D2035”“PH& N LifeTime系列D2040“ [7]“PH& N LifeTime Series D2045”
我看到贾斯汀问为什么他的工作和同样的Q适用于我的解决方案。这似乎更正确:
gsub("([[:alpha:][:punct:]]+\\s)([[:digit:]]+)\\s(.+)", "\\1\\3 \\2", dat2$V1)
答案 1 :(得分:2)
dat< - read.tines('cliboard',sep =',')
gsub('([A-z]+) +([0-9]+) +(.+)$', '\\1 \\3 \\2', dat$V1)
不确定为什么第一组会抓住&虽然...
答案 2 :(得分:2)
text <- c("PH&N 2015 LifeTime Series D",
"PH&N 2020 LifeTime Series D",
"PH&N 2025 LifeTime Series D",
"PH&N 2030 LifeTime Series D",
"PH&N 2035 LifeTime Series D",
"PH&N 2040 LifeTime Series D",
"PH&N 2045 LifeTime Series D")
> ans <- paste(gsub("[0-9]", "", text), as.numeric(gsub("\\D", "", text)))
> gsub(" ", " ", ans) # replace the double space with a single space
[1] "PH&N LifeTime Series D 2015" "PH&N LifeTime Series D 2020"
[3] "PH&N LifeTime Series D 2025" "PH&N LifeTime Series D 2030"
[5] "PH&N LifeTime Series D 2035" "PH&N LifeTime Series D 2040"
[7] "PH&N LifeTime Series D 2045"