heinheo
heinheo

Reputation: 565

Remove elements in list

there is an R list which has sublists - i am indexing with list[[i]] - some from these lists are empty - they are just NULL. How can I remove these and just keep those in which a matrix is stored?

list[[1]]
 [1,]   99   45
  [2,]   92   45
  [3,]   11   45
  [4,]   99   45
  [5,]   92   45
  [6,]   99    2
  [7,]   99   22
  [8,]   99    2

that is okay but

list[[4]] NULL

think

delete.NULLs  <-  function(x.list){   # delele null/empty entries in a list
    x.list[unlist(lapply(x.list, length) != 0)]
}

would work, but that is very slow. My list has 40 million sublists, and I suppose most of them are not having numbers...

Upvotes: 4

Views: 92

Answers (1)

Carlos Cinelli
Carlos Cinelli

Reputation: 11617

You can use Filter. For example:

my_list <- list(A = 10, B = NULL, C = rnorm(10), D = NULL)

#remove nulls
Filter(Negate(is.null), my_list)

Upvotes: 6

Related Questions