Home > Software design >  How to convert a list of tibbles tino a data.frame in R?
How to convert a list of tibbles tino a data.frame in R?

Time:09-14

I have a list of tibbles, I would like to convert into a data.frame, whereas the name of the single tibbles can be taken as a column name

This is an example of list tibbles:

list(`2016-07-20` = structure(list(package = c("filehash", "weathermetrics"
), n = c(179L, 7L)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-2L)), `2016-06-21` = structure(list(package = c("filehash", 
"weathermetrics"), n = c(159L, 6L)), class = c("tbl_df", "tbl", 
"data.frame"), row.names = c(NA, -2L)))

which looks like that:

$`2016-07-20`
# A tibble: 2 × 2
  package            n
  <chr>          <int>
1 filehash         179
2 weathermetrics     7

$`2016-06-21`
# A tibble: 2 × 2
  package            n
  <chr>          <int>
1 filehash         159
2 weathermetrics     6

and I would like it to be converted in such a data.frame:

  package    2016-07-20    2016-06-21 
1 filehash          179           159
2 weathermetrics      7             6

any ideas how can this be done?

i have already tried do.call, unlist or t(sapply), but none helped me reached the desired goal.

thanks

Assa

CodePudding user response:

You can do:

library(dplyr)
library(tidyr)

l %>% 
  bind_rows(.id = "date") %>% 
  pivot_wider(names_from = "date", values_from = "n")

output

  package        `2016-07-20` `2016-06-21`
1 filehash                179          159
2 weathermetrics            7            6

CodePudding user response:

In base R:

cbind(l[[1]][1], sapply(l, '[[', 2))

CodePudding user response:

If the package columns of those data in the list are not identical to one another, left_join() or merge() are more suitble than cbind.

library(dplyr)
library(purrr)

lst %>%
  imap(~ rename(.x, !!.y := n)) %>%
  reduce(left_join, by = "package")

# A tibble: 2 × 3
  package        `2016-07-20` `2016-06-21`
  <chr>                 <int>        <int>
1 filehash                179          159
2 weathermetrics            7            6

CodePudding user response:

using data.table

library(data.table)

dcast(rbindlist(l, idcol = T), package ~ .id, value.var = "n")

#           package 2016-06-21 2016-07-20
# 1:       filehash        159        179
# 2: weathermetrics          6          7
  • Related