从R中的列表中删除“”元素

时间:2015-01-27 20:38:55

标签: r

我有一个列表,我想删除空字符:""

我似乎错误地对元素进行了分类:

> sample2[which(sample2 == "")]
list()
> sample2[which(sample2 != "")]
[[1]]
 [1] ""          "03JAN1990" ""          ""          ""         
 [6] ""          "23.4"      "0.4"       ""          ""         
[11] ""          ""          "25.1"      "0.3"       ""         
[16] ""          ""          ""          "26.6"      "0.0"      
[21] ""          ""          ""          ""          "28.6"     
[26] "0.3"   

我该如何分配和删除空字符?

2 个答案:

答案 0 :(得分:6)

从您的输出中,看起来sample2不是字符向量,但它是包含字符向量的列表。你应该使用

sample2[[1]][which(sample2[[1]] != "")]

(包括dput(sample2)只是为了确认)

或者甚至更好,首先从列表中取出字符向量

sample3 <- sample2[[1]]
# or maybe sample3 <- unlist(sample2)
sample3[which(sample3 != "")]

答案 1 :(得分:1)

一个非常基本的解决方案:

> lst = list(1,2,"dog","","boss","")
> x = unlist(lst)
> list(x[x!=""])
[[1]]
[1] "1"    "2"    "dog"  "boss"