我想使用strsplit()x = "a,b,"
将字符串(最后一个位置的逗号)拆分为向量。c("a","b","")
结果是:
>strsplit(x,',')
[[1]]
[1] "a" "b"
我想要第三个组件(空字符串或 NULL)。
该功能read.csv(x)
可以管理它,但我仍然认为它strsplit()
应该像我预期的那样运行。Python 提供c("a","b","")
.
也许有一些strsplit()
我不知道的选择?
这就是它的工作原理,并记录在帮助(strsplit)中:
Note that this means that if there is a match at the beginning of a (non-empty) string, the first element of the output is ‘""’, but if there is a match at the end of the string, the output is the same as with the match removed.
您可能希望str_split
从stringr
包中使用:
> require(stringr)
> str_split("a,b,",",")
[[1]]
[1] "a" "b" ""
> str_split("a,b",",")
[[1]]
[1] "a" "b"
> str_split(",a,b",",")
[[1]]
[1] "" "a" "b"
> str_split(",a,b,,,",",")
[[1]]
[1] "" "a" "b" "" "" ""