【发布时间】:2019-10-01 14:41:33
【问题描述】:
R 的strsplit 在“空”时删除最后一个元素(示例 2),但不是在第一次出现时(示例 3)或在要拆分的向量中间(示例 4)。
> unlist(strsplit(x = "1,4", split = ",")) #Example 1
[1] "1" "4"
> unlist(strsplit(x = ",4", split = ",")) #Example 2
[1] "" "4"
> unlist(strsplit(x = "1,", split = ",")) #Example 3
[1] "1"
> unlist(strsplit(x = "1,,,4", split = ",")) #Example 4
[1] "1" "" "" "4"
有没有办法解析字符串,允许在拆分后保留最后一个元素(如果为空):
> strmagic(x = "1,", split = ",") #strmagic being the wanted function
[1] "1" ""
其他包的解决方案是here(似乎)。可以在base R中完成吗?
更新
是否需要添加一个填充元素然后是一个 la:
strmagic <- function(v, sep)lapply(v, function(x)head(unlist(strsplit(paste(x, "-", sep = sep), split = sep)), -1))
【问题讨论】:
-
你可以在
x的末尾添加一个,,当没有逗号结束字符串但不是很有效时,使用stringr