Stripping NULLs recursively from an R list

Is there a nicer way to do this in R?

stripNullRecursively <- function(x) {
  if (class(x) != "list") {
    return(x)
  }
  x <- lapply(x, stripNullRecursively)
  return(x[names(x)[sapply(x, function(v) !(is.null(v) | (is.list(v) & length(v) == 0)))]])
}

I have a list where some elements are themselves lists (of lists of lists, etc.) I want to ignore entries with NULL as well as entries that are empty after stripping NULLs.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *