如何按值或类型从列表中删除元素

4

我有一个包含列表和NAs的列表。我想过滤掉NAs,但我不知道NAs的确切名称或位置。

我搜索了很多,但只找到了如何按名称或索引删除元素的方法,但这不是我要找的。

这是我的列表的一个示例:

example <- list(list(1,2,3), list(2,3,4), NA, list(2,3,4))

我的输出结果看起来像这样:

Name      Type        Value
example   list[[4]]   List of length 4
  [[1]]   list[[3]]   List of length 3
  [[2]]   list[[3]]   List of length 3
  [[3]]   logical     NA               <-I'd like to remove this row
  [[4]]   list[[3]]   List of length 3

我想编写一个循环,如果值为“NA”或类型为“logical”,则从我的列表中删除元素。非常感谢您的帮助!
3个回答

4
这取决于你的数据结构。对于你的例子,下面的方法可以使用:
example[!is.na(example) & !is.logical(example)]

如果子列表中包含您想要删除的NA,则情况会变得更加复杂。


3
这是一种简单的方法,用于从R列表中删除NA值。 example <- example[!is.na(example)]

3

您可以使用 which 函数查找 NA 元素的索引,然后按照索引将其移除:

example[-which(is.na(example))]

谢谢您的快速回复!说实话,我不太清楚如何做,which(example$Value == NA) 不起作用。您能给我一些提示吗? - Merle
你需要使用 is.na()。 - Elin
非常感谢! :-) - Merle
你不需要使用 which,可以直接使用 example[!is.na(example)] - Jake Kaupp
@JakeKaupp 没错,但我认为在这个网站上建议不同的答案并讨论每个解决方案的优缺点是很好的。 - Dandelion
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接