在字符串中第一个逗号处分割

11
我该如何使用base高效地在第一个逗号处拆分以下字符串?
x <- "I want to split here, though I don't want to split elsewhere, even here."
strsplit(x, ???)

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

[[1]]
[1] "I want to split here"   "though I don't want to split elsewhere, even here."

感谢您的提前帮助。
编辑:没想到要提到这个。这需要能够推广到一个列、字符串向量,如下所示:
y <- c("Here's comma 1, and 2, see?", "Here's 2nd sting, like it, not a lot.")

结果可以是两列或一个长向量(我可以取每隔一个元素),或者是一个字符串列表,其中每个索引([n])有两个字符串。
对于缺乏清晰度的问题,我们深表歉意。

非常hacky,但是像list(head(y[[1]],1), paste(tail(y[[1]],-1), collapse = ","))这样的东西怎么样?其中ystrsplit(x, ...)的输出? - Chase
Chase,我尝试过了,但似乎无法处理类似字符串的向量。我编辑了原帖以进一步解释问题。 - Tyler Rinker
str_locate_all(string=y, ',') 将找到您模式(在此为逗号)的所有索引位置,然后可以将其应用于从向量或列中进行选择。 - John
5个回答

13

以下是我可能会采取的做法。这种做法可能看起来有点笨拙,但由于 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."

@josh-obrien 你如何扩展那段代码以去除[2]中的前导空格? - John
1
我将使用 gsub("^\\s+|\\s+$", "", JOSH的STUFF) 进行包装。 - Tyler Rinker
我喜欢它,Josh。它很有效,而且相当简单,保持在基础中。谢谢你。+1 - Tyler Rinker
1
你可以使用 any(grepl(XX,x)) 来检查你的 XX 是否正确。如果返回 FALSE,那么就是正确的。 - Marek
2
@established1969 -- 要去除逗号后面的空格,我会使用 strsplit(sub(",\\s*", XX, x), XX) - Josh O'Brien

10

来自于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."

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

4

这里有另一种解决方案,使用正则表达式来捕获第一个逗号前后的内容。

x <- "I want to split here, though I don't want to split elsewhere, even here."
library(stringr)
str_match(x, "^(.*?),\\s*(.*)")[,-1] 
# [1] "I want to split here"                              
# [2] "though I don't want to split elsewhere, even here."

3

库(stringr)

str_sub(x, end = min(str_locate(string=x, ',')-1))

这将获取你想要的第一部分。更改str_sub中的start=end=,以获取其他你想要的内容。

例如:

str_sub(x,start = min(str_locate(string=x, ',')+1 ))

并在str_trim中包裹,以去除前导空格:

str_trim(str_sub(x,start = min(str_locate(string=x, ',')+1 )))


2
这个可以正常运行,但我更喜欢Josh Obrien的方法:
y <- strsplit(x, ",")
sapply(y, function(x) data.frame(x= x[1], 
    z=paste(x[-1], collapse=",")), simplify=F))

受Chase回答的启发。

有些人提供了非基础的方法,所以我想我会添加我通常使用的方法(尽管在这种情况下我需要一个基础响应):

y <- c("Here's comma 1, and 2, see?", "Here's 2nd sting, like it, not a lot.")
library(reshape2)
colsplit(y, ",", c("x","z"))

在第一部分中,我不明白为什么你要使用sapply而不是seq_along(y),而不只是y。你似乎从未需要显式地使用索引。另外,看起来你删除了所有逗号,即使你想要在其他字符串中保留它们? - Dason

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接