Assa Yeroslaviz
Assa Yeroslaviz

Reputation: 764

How to convert a list of tibbles tino a data.frame in R?

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

Upvotes: 2

Views: 957

Answers (4)

Merijn van Tilborg
Merijn van Tilborg

Reputation: 5897

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

Upvotes: 1

Darren Tsai
Darren Tsai

Reputation: 35604

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

Upvotes: 2

Ma&#235;l
Ma&#235;l

Reputation: 52359

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

Upvotes: 3

Robert Hacken
Robert Hacken

Reputation: 4725

In base R:

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

Upvotes: 3

Related Questions