问题描述
如何使用 base 有效地在第一个逗号上拆分以下字符串?
How can I efficiently split the following string on the first comma using base?
x <- "I want to split here, though I don't want to split elsewhere, even here."
strsplit(x, ???)
预期结果(2 个字符串):
Desired outcome (2 strings):
[[1]]
[1] "I want to split here" "though I don't want to split elsewhere, even here."
提前致谢.
没想到提到这个.这需要能够推广到一列,像这样的字符串向量,如:
Didn't think to mention this. This needs to be able to generalize to a column, vector of strings like this, as in:
y <- c("Here's comma 1, and 2, see?", "Here's 2nd sting, like it, not a lot.")
结果可以是两列或一个长向量(我可以采用其中的所有其他元素)或一个字符串列表,其中每个索引 ([[n]]) 具有两个字符串.
The outcome can be two columns or one long vector (that I can take every other element of) or a list of stings with each index ([[n]]) having two strings.
对不够清晰表示歉意.
推荐答案
这就是我可能会做的.它可能看起来很笨拙,但由于 sub()
和 strsplit()
都是矢量化的,因此在处理多个字符串时它也能顺利工作.
Here's what I'd probably do. It may seem hacky, but since sub()
and strsplit()
are both vectorized, it will also work smoothly when handed multiple strings.
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."
这篇关于拆分字符串中的第一个逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!