Nautica
Nautica

Reputation: 2018

Flattening a list of data frames into one data frame with purrr::flatten_dfr

library(tidyverse)

test_list <- list(a = data.frame("fruits" = fruit[1:10],
                                 "letters" = letters[1:10],
                                 "numbers" = rnorm(10)),
                  b = data.frame("fruits" = fruit[1:12],
                                 "letters" = letters[1:12],
                                 "numbers" = rnorm(12)),
                  c = data.frame("fruits" = fruit[1:7],
                                 "letters" = letters[1:7],
                                 "numbers" = rnorm(7)),
                  d = data.frame("fruits" = fruit[1:12],
                                 "letters" = letters[1:12],
                                 "numbers" = rpois(12, 2)))

I have a list of data frames with the same structure of columns but with different number of rows in each df. I just want to flatten them in to one data frame. I figured I could just use something like purrr::flatten_dfr():

flatteneddf <- flatten_dfr(test_list)

However this throws an issue with the row length of each df:

Error in bind_rows_(x, .id) : Argument 4 must be length 10, not 12

I know there are many other options available to flatten list of dfs but I just want to know why this option isn't working.

Upvotes: 0

Views: 1480

Answers (1)

arg0naut91
arg0naut91

Reputation: 14764

Try:

library(tidyverse)

df <- bind_rows(test_list)

I'm not sure there is a way you can solve this with flatten_dfr.

For example, even if you'd have the same length of all dataframes, flatten_dfr would just return one of them.

If the column names would be different and length the same, flatten_dfr would bind those with completely different names, therefore mimicking the behaviour of bind_cols.

Perhaps someone else has a specific use case for flatten_dfr, but I think in the end what you'll end up using is either bind_rows or bind_cols.

Upvotes: 3

Related Questions