我的数据框架如下:
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
Run Code Online (Sandbox Code Playgroud)
我们可以看到名称和年龄是相同的值.所以我想用字符串中的最后两个字符拆分它:
height name age
1 190 John Smith 34
2 165 Mr.Turner 54
3 174 Antonio P. 23
4 176 John Brown 31
Run Code Online (Sandbox Code Playgroud)
我怎么能这样做?
tidyr::separate通过允许您传递拆分位置的整数索引(包括从字符串末尾进行负索引),使分隔列变得简单.(当然,正则表达式也适用.)
library(tidyr)
b %>% separate(name, into = c('name', 'age'), sep = -4, convert = TRUE)
## height name age
## 1 190 John Smith 34
## 2 165 Mr.Turner 54
## 3 174 Antonio P. 23
## 4 176 John Brown 31
Run Code Online (Sandbox Code Playgroud)
或者在最后的空间分开:
b %>% separate(name, into = c('name', 'age'), sep = '\\s(?=\\S*?$)', convert = TRUE)
Run Code Online (Sandbox Code Playgroud)
返回相同的东西.
在基础R中,它的工作量更多:
b$name <- as.character(b$name)
split_name <- strsplit(b$name, '\\s(?=\\S*?$)', perl = TRUE)
split_name <- do.call(rbind, split_name)
colnames(split_name) <- c('name', 'age')
b <- data.frame(b[-2], split_name, stringsAsFactors = FALSE)
b$age <- type.convert(b$age)
b
## height name age
## 1 190 John Smith 34
## 2 165 Mr.Turner 54
## 3 174 Antonio P. 23
## 4 176 John Brown 31
Run Code Online (Sandbox Code Playgroud)