我想通过句点拆分以下字符串。 我尝试使用strsplit()
和"."
参数中的split
,但没有得到我想要的结果。
s <- "I.want.to.split"
strsplit(s, ".")
[[1]]
[1] "" "" "" "" "" "" "" "" "" "" "" "" "" "" ""
我想要的输出结果是将s
分割成一个包含4个元素的列表,如下所示。
[[1]]
[1] "I" "want" "to" "split"
我该怎么办?
在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)
以获取更多信息。
strsplit()
,你还可以使用 scan()
。尝试一下:scan(what = "", text = s, sep = ".")
# Read 4 items
# [1] "I" "want" "to" "split"