【发布时间】:2016-10-01 21:09:14
【问题描述】:
我的数据框看起来像:
b <- data.frame(height = c(190,165,174,176), name = c('John Smith 34','Mr.Turner 54', 'Antonio P. 23', 'John Brown 31'))
# height name
# 1 190 John Smith 34
# 2 165 Mr.Turner 54
# 3 174 Antonio P. 23
# 4 176 John Brown 31
我们可以看到 name 和 age 是相同的值。所以我想用字符串中的最后两个字符来分割它:
height name age
1 190 John Smith 34
2 165 Mr.Turner 54
3 174 Antonio P. 23
4 176 John Brown 31
我该怎么做?
【问题讨论】:
-
我会在最后一个空格上分开,因为年龄有时可以是三位数。见stackoverflow.com/questions/19959697/…
-
library(tidyr) ; b %>% separate(name, into = c('name', 'age'), sep = -3, convert = TRUE) -
或
b <- cbind(b[-2], setNames(as.data.frame(do.call(rbind, strsplit(as.character(b$name), '.(?=..$)', perl = T)), stringsAsFactors = FALSE), c('name', 'age'))) ; b$age <- type.convert(b$age),但这需要更多的努力。 -
@alistaire,非常感谢!
-
cbind(b[1], read.csv(text = gsub(' (..)$', ',\\1', b$name), header = FALSE))