在字符串中的第一个逗号上拆分

Tyl*_*ker 8 regex r

如何使用base在第一个逗号上有效地拆分以下字符串?

x <- "I want to split here, though I don't want to split elsewhere, even here."
strsplit(x, ???)
Run Code Online (Sandbox Code Playgroud)

期望的结果(2个字符串):

[[1]]
[1] "I want to split here"   "though I don't want to split elsewhere, even here."
Run Code Online (Sandbox Code Playgroud)

先感谢您.

编辑:没想到要提这个.这需要能够推广到一个列,像这样的字符串向量,如:

y <- c("Here's comma 1, and 2, see?", "Here's 2nd sting, like it, not a lot.")
Run Code Online (Sandbox Code Playgroud)

结果可以是两列或一个长向量(我可以采用其他所有元素)或每个索引([[n]])具有两个字符串的stings列表.

对于缺乏清晰度表示道歉.

Jos*_*ien 11

这是我可能会做的.它可能看起来很hacky,但既然sub()并且strsplit()都是矢量化的,那么在传递多个字符串时它也会顺利运行.

XX <- "SoMeThInGrIdIcUlOuS"
strsplit(sub(",\\s*", XX, x), XX)
# [[1]]
# [1] "I want to split here"                               
# [2] "though I don't want to split elsewhere, even here."
Run Code Online (Sandbox Code Playgroud)

  • @ established1969 - 为了修饰逗号之后的空格,我会做`strsplit(sub(",\\ s*",XX,x),XX)`. (2认同)

flo*_*del 8

stringr包装:

str_split_fixed(x, pattern = ', ', n = 2)
#      [,1]                  
# [1,] "I want to split here"
#      [,2]                                                
# [1,] "though I don't want to split elsewhere, even here."
Run Code Online (Sandbox Code Playgroud)

(这是一个有一行两列的矩阵.)