R排序数据,但不包括空白rowname

时间:2016-02-15 15:24:06

标签: regex r grep

我有一组带有rownames的数据,这些数据包含2组数据作为名称,用逗号分隔。有没有办法对空白单词进行排序并仅返回该行?

*编辑为数据中有两个以上的条目,之前的答案不超过两个条目

z <- c("apple,new,tree")
z <- rbind(z,"apple,new")

z[grep(paste0(",","",".*"),z)]

输出

> z[grep(paste0(",","",".*"),z)]
[1] "apple,new,tree" "apple,new" 

期望输出

> z[grep(paste0(",","",".*"),z)]
[1] "apple,new" 

1 个答案:

答案 0 :(得分:1)

没有正则表达式的另一种方法:

> z[sapply(strsplit(z,","),length)==1]
[1] "apple,"

编辑:这是一个更通用的解决方案,适用于任何此类数据集,前提是逗号位于正确的位置。

z <- "apple,new,tree"
z <- c(z,"apple,new,")
z <- c(z,"apple,,tree")

z[sapply(strsplit(paste0(z,","),","),function(x) any(x==""))]
[1] "apple,new,"  "apple,,tree"

如果您在某些条目的末尾缺少逗号,则会变得更复杂,但您会明白这一点。