字符串拆分为R中的最后一个逗号

时间:2014-07-24 15:58:03

标签: r string split comma

我不是R的新手,但我对正则表达方式相对较新。

类似的问题可以在here中找到。

一个例子是我使用

> strsplit("UK, USA, Germany", ", ")
[[1]]
[1] "UK"      "USA"     "Germany"

但我想得到

[[1]]
[1] "UK, USA"     "Germany"

另一个例子是

> strsplit("London, Washington, D.C., Berlin", ", ")
[[1]]
[1] "London"     "Washington" "D.C."       "Berlin"  

我希望得到

[[1]]
[1] "London, Washington, D.C."       "Berlin"  

绝对华盛顿,D.C。不应该分成两部分,只能用最后一个逗号分隔 ,而不是每个逗号。

我认为一种可行的方法是用其他东西替换最后一个逗号,例如

$, #, *, ...

然后使用

strsplit() 

将您所替换的字符串拆分(确保它是唯一的!),但如果您可以直接使用某些内置函数处理问题,我会更高兴。

那我怎么能这样做?非常感谢

2 个答案:

答案 0 :(得分:11)

这是一种方法:

strsplit("UK, USA, Germany", ",(?=[^,]+$)", perl=TRUE)

## [[1]]
## [1] "UK, USA" " Germany"

您可能需要:

strsplit("UK, USA, Germany", ",\\s*(?=[^,]+$)", perl=TRUE)

## [[1]]
## [1] "UK, USA" "Germany"

如果逗号后面没有空格,它将匹配:

strsplit(c("UK, USA, Germany", "UK, USA,Germany"), ",\\s*(?=[^,]+$)", perl=TRUE)

## [[1]]
## [1] "UK, USA" "Germany"
## 
## [[2]]
## [1] "UK, USA" "Germany"

答案 1 :(得分:6)

您可以使用stri_split

中的stringi功能
x <- "USA,UK,Poland"
stri_split_fixed(x,",") # standard split by comma
[[1]]
[1] "USA"    "UK"     "Poland"

stri_split_fixed(x,",",n = 2) # set the max number of elements
[[1]]
[1] "USA"       "UK,Poland"

不幸的是,没有参数来改变分裂的起点(从开始/结束),但我们可以用另一种方式处理 - 使用stri_reverse

stri_split_fixed(stri_reverse(x),",",n = 2) #reverse
[[1]]
[1] "dnaloP" "KU,ASU"

stri_reverse(stri_split_fixed(stri_reverse(x),",",n = 2)[[1]]) #reverse back
[1] "Poland" "USA,UK"
stri_reverse(stri_split_fixed(stri_reverse(x),",",n = 2)[[1]])[2:1] #and again :)
[1] "USA,UK" "Poland"