Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove empty list from a list of lists

Tags:

list

r

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).

The code i'm trying is:

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

But this does not work.

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

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

Any help is appreciated

like image 251
Sander Van der Zeeuw Avatar asked Dec 26 '22 07:12

Sander Van der Zeeuw


1 Answers

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

l[!is.na(l)]

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)

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

Filter(Negate(is.na), l)
like image 196
Arun Avatar answered Jan 07 '23 18:01

Arun