Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manipulate NULL elements in a nested list?

Tags:

list

r

I have a nested list containing NULL elements, and I'd like to replace those with something else. For example:

l <- list(
  NULL,
  1,
  list(
    2,
    NULL,
    list(
      3,
      NULL
    )
  )
)

I want to replace the NULL elements with NA. The natural way to do this is to recursively loop over the list using rapply. I tried:

rapply(l, function(x) NA, classes = "NULL", how = "replace")
rapply(l, function(x) if(is.null(x)) NA else x, how = "replace")

Unfortunately, neither of these methods work, since rapply apparently ignores NULL elements.

How can I manipulate the NULL elements in a nested list?

like image 574
Richie Cotton Avatar asked Aug 15 '16 06:08

Richie Cotton


People also ask

Can we assign null to list?

Solution. Yes, We can insert null values to a list easily using its add() method. In case of List implementation does not support null then it will throw NullPointerException.

What is known as nested list?

A nested list is a list that appears as an element in another list. In this list, the element with index 3 is a nested list. If we print( nested[3] ), we get [10, 20] . To extract an element from the nested list, we can proceed in two steps.


1 Answers

I'm going to go with "use a version of rapply doesn't doesn't have weird behaviour with NULL". This is the simplest implementation I can think of:

simple_rapply <- function(x, fn)
{
  if(is.list(x))
  {
    lapply(x, simple_rapply, fn)
  } else
  {
    fn(x)
  }
}

(rawr::rapply2, as mentioned in the comments by @rawr is a more sophisticated attempt.)

Now I can do the replacement using

simple_rapply(l, function(x) if(is.null(x)) NA else x)
like image 181
2 revs Avatar answered Oct 16 '22 07:10

2 revs