简体   繁体   English

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

[英]Removing “” elements from a list in R

I have a list where I would like to remove empty characters: "" . 我有一个要删除空字符的列表: ""

I seem to be subsetting the elements incorrectly: 我似乎在错误地对元素进行了细分:

> 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"   

What should I do to subset and remove the empty characters? 我该怎么做才能分组并删除空字符?

From your output, it looks like sample2 is not a character vector, but it is a list containing a character vector. 从您的输出,看起来sample2不是一个字符向量,但它是一个包含字符向量的列表。 You should be using 你应该使用

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

(It would help to include dput(sample2) just to confirm) (这有助于包括dput(sample2)只是为了确认)

Or even better, take the character vector out of the list first 或者甚至更好,首先从列表中取出字符向量

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

A very basic solution: 一个非常基本的解决方

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM