Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retain empty lists in rrapply::rrapply()

Tags:

r

Is there an option that allows me to retain list entries that have values that are 0-length lists in the how="melt" option? In the below, I'd like to retain the B and E entries.

Note: @akrun gave an initial solution when I had a simpler reprex here (I did not have the 0-length list at E in the original). I originally accepted, realized I needed a more complex example, and used @akrun 's solution as a basis to my accepted solution below.

library(rrapply)
lst <- list(A=1, B=list(), C=list(D=letters[1:3], E=list()))
str(lst)
#> List of 3
#>  $ A: num 1
#>  $ B: list()
#>  $ C:List of 2
#>   ..$ D: chr [1:3] "a" "b" "c"
#>   ..$ E: list()

# Melting it drops things that has 0-length lists, like B and E:
rrapply(lst, how="melt")
#>   L1   L2   value
#> 1  A <NA>       1
#> 2  C    D a, b, c

Created on 2023-04-27 with reprex v2.0.2

like image 550
mpettis Avatar asked Feb 02 '26 21:02

mpettis


1 Answers

The empty list elements can be recursively changed to NA and then melt

rrapply(lst, classes = "list", f = \(x) if(!length(x)) NA else x) |>
    rrapply(how = "melt")

-output

  L1   L2   value
1  A <NA>       1
2  B <NA>      NA
3  C    D a, b, c
like image 158
akrun Avatar answered Feb 05 '26 12:02

akrun