Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unnest list and gather items with purrr

Tags:

r

purrr

tidyverse

I have a list like:

list(list(goals = c(42L, 52L, 55L), 
          season = "88", 
          player = c("a", "b","c")), 
     list(goals = c(41L,53L, 37L, 40L), 
          season = "89", 
          player = c("a","b", "c", "d")))

I want to convert this to a dataframe in long format like:

goals player season 
42    a      88
52    b      88
.
.
41    a      89
53    b      89
.

I can achieve this using plyr like: plyr::ldply(mylist, data.frame, .id="season"

I'm thinking there is probably an updated way of doing this using purrr ordplyr?

like image 322
Domino55 Avatar asked Jan 04 '19 04:01

Domino55


2 Answers

We can do this by converting the list elements to tibble by looping through the list using map

library(tidyverse)
lst1 %>%
    map_df(as_tibble)
# A tibble: 7 x 3
#  goals player season
#  <dbl> <chr>   <dbl>
#1    42 a          88
#2    52 b          88
#3    55 c          88
#4    41 a          89
#5    53 b          89
#6    37 c          89
#7    48 d          89

A base R option would be to convert to a list of data.frames and then rbind

do.call(rbind, lapply(lst1, as.data.frame))

data

lst1 <- list(list(goals = c(42, 52, 55), player = c("a", "b", "c"), season = 88), 
     list(goals = c(41, 53, 37, 48), player = c("a", "b", "c", 
     "d"), season = 89))
like image 76
akrun Avatar answered Oct 27 '22 14:10

akrun


Another way of doing it using do.call, rbind and Map from base R with as_tibble from dplyr:

do.call(rbind,Map(as_tibble,lst1))
# A tibble: 7 x 3
  goals season player
  <int> <chr>  <chr> 
1    42 88     a     
2    52 88     b     
3    55 88     c     
4    41 89     a     
5    53 89     b     
6    37 89     c     
7    40 89     d    
like image 36
PT2018 Avatar answered Oct 27 '22 15:10

PT2018