用R中的最后两个字符分割字符串? (/负字符串索引) [英] Split string by last two characters in R? (/negative string indices)

查看:109
本文介绍了用R中的最后两个字符分割字符串? (/负字符串索引)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据框看起来像:

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

我们可以看到名称和年龄是相同的值。因此,我想用字符串中的最后两个字符将其分割:

As we can see name and age are the same value. So I want to split it by last two characters in string:

  height       name age
1    190 John Smith  34
2    165  Mr.Turner  54
3    174 Antonio P.  23
4    176 John Brown  31

我该怎么做?

推荐答案

tidyr :: separate 通过允许您传递拆分位置的整数索引(包括从字符串末尾开始的负索引),使分隔列变得简单。 (当然,正则表达式也起作用。)

tidyr::separate makes separating columns simple by allowing you to pass an integer index of split position, including negatively indexed from the end of the string. (Regex works as well, of course.)

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

或以空格分隔:

b %>% separate(name, into = c('name', 'age'), sep = '\\s(?=\\S*?$)', convert = TRUE)

返回相同的内容。

在基数R中,还有更多工作:

In base R, it's a bit more work:

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

这篇关于用R中的最后两个字符分割字符串? (/负字符串索引)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆