Efficiently remove all NULL values in a list and all sublists

前端 未结 2 1021
旧巷少年郎
旧巷少年郎 2021-01-17 08:48

Consider the following list:

> l1 <- list(NULL,1,2,list(NULL,3,list(NULL,4)))
> str(l1)
List of 4
 $ : NULL
 $ : num 1
 $ : num 2
 $ :List of 3
  ..         


        
2条回答
  •  心在旅途
    2021-01-17 09:26

    This can be done recursively:

    rmNull <- function(x) {
       x <- Filter(Negate(is.null), x)
       lapply(x, function(x) if (is.list(x)) rmNull(x) else x)
    }
    l2 <- rmNull(l1)
    

    giving:

    > str(l2)
    List of 3
     $ : num 1
     $ : num 2
     $ :List of 2
      ..$ : num 3
      ..$ :List of 1
      .. ..$ : num 4
    

提交回复
热议问题