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
?
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.frame
s and then rbind
do.call(rbind, lapply(lst1, as.data.frame))
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))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With