JorisChau/rrapply

analogue for tidyr::unnest_longer

reikoch opened this issue · 2 comments

I think it would be nice if there were an option in rrapply to do what tidyr::unnest_longer can do in the following case:

xx <- tibble(site=LETTERS[1:4], numbers=list(1:2, 1:4, 1:2, 1:3))
expand <- tidyr::unnest_longer(xx, col='numbers')

This transforms the structure

tibble [4 × 2] (S3: tbl_df/tbl/data.frame)
 $ site   : chr [1:4] "A" "B" "C" "D"
 $ numbers:List of 4
  ..$ : int [1:2] 1 2
  ..$ : int [1:4] 1 2 3 4
  ..$ : int [1:2] 1 2
  ..$ : int [1:3] 1 2 3

to the structure

tibble [11 × 2] (S3: tbl_df/tbl/data.frame)  
$ site   : chr [1:11] "A" "A" "B" "B" ...  
$ numbers: int [1:11] 1 2 1 2 3 4 1 2 1 2 ...

Whatever I tried - I did not manage to replicate this transformation in rrapply.

I might include an option in the future to unnest nested lists into mixed long/wide formats, but I first need to figure out how this would work exactly for general deeply nested lists (which does not seem so obvious to me). For simple nested data.frame columns this is also straightforward in base-R, e.g.:

with(xx, stack(setNames(numbers, site)))
#>    values ind
#> 1       1   A
#> 2       2   A
#> 3       1   B
#> 4       2   B
#> 5       3   B
#> 6       4   B
#> 7       1   C
#> 8       2   C
#> 9       1   D
#> 10      2   D
#> 11      3   D

Beautiful - I completely did not think of stack()! But in real settings I encounter e.g. matrices and dataframes, not vectors.

Clearly a more general solution is a challenge to design; the escape via tidyr's unnest() functions does the trick, not sure whether it is worth to create another solution...