从列表列表中删除空列表 [英] Remove empty list from a list of lists

查看:98
本文介绍了从列表列表中删除空列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表列表,其中有些是NA例如empty lists.我要提取所有填充有数据的列表,并删除所有empty(NA)的列表.

I have a list of lists where some of them are NA e.g. empty lists. I want to extract all the lists which are filled with data and remove all the lists which are empty(NA).

我正在尝试的代码是:

lapply(outputfile,function(x){
  if(outputfile != NA){
  test<-lapply(outputfile,unlist)
}})

但这不起作用.

列表列表如下:(随机数据的小示例)

The list of lists is like this: (small example of random data)

list(NA, NA, NA, NA, NA, NA, list(c(5, 5, 5, 5, 5, 5, 5, 5, 5, 
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5)))

我只想提取其中包含5s的列表.前6个列表应被忽略,例如删除.

I only want to extract the list with the 5s in it. The first 6 lists should be ignored e.g. removed.

感谢您的帮助

推荐答案

因此,要在第一级删除NA,可以直接使用is.na:

So, to remove NA at the first level, you could use is.na directly:

l[!is.na(l)]

或者,您也可以使用Filter尝试将被求函数的结果强制为逻辑并返回那些被求为TRUE的元素.您可以这样做,例如:

Alternatively, you can also use Filter which tries to coerce the results of the evaluated function to logical and returns those elements that evaluated to TRUE. You could do, for example:

Filter(function(x) !is.na(x), l)

(或)等效(如@flodel在评论下写)

(or) equivalently (as @flodel writes under comment)

Filter(Negate(is.na), l)

这篇关于从列表列表中删除空列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆