【发布时间】:2012-04-25 03:51:03
【问题描述】:
如何使用 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 = ","))这样y是strsplit(x, ...)的输出呢? -
Chase 我试过了,但似乎无法让它适用于类似字符串的向量。我编辑了我的原始帖子以进一步解释问题。
-
str_locate_all(string=y, ',')将找到您的模式的所有索引位置(在您的情况下为逗号),然后可以将其应用于从向量或列中进行选择。