如何使用strsplit函数分割句点。

43

我想通过句点拆分以下字符串。 我尝试使用strsplit()"."参数中的split,但没有得到我想要的结果。

s <- "I.want.to.split"
strsplit(s, ".")
[[1]]
 [1] "" "" "" "" "" "" "" "" "" "" "" "" "" "" ""

我想要的输出结果是将s分割成一个包含4个元素的列表,如下所示。

[[1]]
[1] "I"     "want"  "to"    "split"

我该怎么办?

3个回答

54

strsplit()函数的split参数中使用正则表达式时,需要用\\.转义.,或者使用字符类[.]。否则,将会使用.作为其特殊含义的字符,表示"任何单个字符"。

s <- "I.want.to.split"
strsplit(s, "[.]")
# [[1]]
# [1] "I"     "want"  "to"    "split"

但在这里更有效的方法是使用strsplit()中的fixed参数。使用此参数将绕过正则表达式引擎并搜索"."的完全匹配项。

strsplit(s, ".", fixed = TRUE)
# [[1]]
# [1] "I"     "want"  "to"    "split"

当然,您可以查看help(strsplit)以获取更多信息。


5
你需要将点号.放在字符类内,或者在其前面加上两个反斜杠进行转义,因为点号是正则表达式中具有特殊含义的字符,意味着“匹配任何单个字符(除换行符外)”。
s <- 'I.want.to.split'
strsplit(s, '\\.')
# [[1]]
# [1] "I"     "want"  "to"    "split"

1
除了使用 strsplit(),你还可以使用 scan()。尝试一下:
scan(what = "", text = s, sep = ".")
# Read 4 items
# [1] "I"     "want"  "to"    "split"

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