Hide the nested list in the 1st list

I am looking for an effective solution (recursively) to smooth a nested list (of arbitrary depth) into a non-nested, 1 deep list. The elements of the list are not homogeneous, therefore they should not be listed in the vector (which will force all values ​​to the same type). The best solution:

flatlist <- function(mylist){
    lapply(rapply(mylist, enquote, how="unlist"), eval)
}

This is almost what I want:

> flatlist(list(foo=TRUE, bar=456, pets=list(cat="meeuw", dog="woof")))
$foo
[1] TRUE

$bar
[1] 456

$pets.cat
[1] "meeuw"

$pets.dog
[1] "woof"

However, the problem is what rapplyoutputs the values NULL, which is undesirable:

> flatlist(list(foo=123, bar=NULL))
$foo
[1] 123

I would like the elements to NULLbe displayed on the output, either as NULL, or how NA. Also double looping with enquoteand then evalmakes things a little slow. This feature is widely used in my code. Is there a way to do all this in one go?

+4
1

rapply , NULL :

renquote <- function(l) if (is.list(l)) lapply(l, renquote) else enquote(l)

lapply(unlist(renquote(ml)), eval)
+4

All Articles