Home > Blockchain >  How do I combine data frames in a dataset that is a list, to create one full dataset?
How do I combine data frames in a dataset that is a list, to create one full dataset?

Time:06-10

I have a dataset which is a list containing 1000 items that are data frames. I want to unlist these data frames using a loop such that the end result is one large data frame with each element of the data set stacked upon one another. I've made a jovial example below:

list1 <- data.frame(x = c("hello","bye"), y = c(1, 4), z = c(TRUE, FALSE)) 
list2 <- data.frame(x = c("bye","hello"), y = c(5, 8), z = c(FALSE, FALSE)) 
fulllist <- list(list1, list2)

As mentioned above I'm wanting to make 'fulllist' into a data frame using a loop as seen below. Thanks in advance

x y z
hello 1 TRUE
bye 4 FALSE
bye 5 FALSE
hello 8 FALSE

CodePudding user response:

bind_rows from dplyr can take a list of dataframes as input:

dplyr::bind_rows(fulllist)

CodePudding user response:

You should not really be handling that many data frames though, but here's a possible solution given that you have list1, list2 and so on ...

list1 <- data.frame(x = c("hello","bye"), y = c(1, 4), z = c(TRUE, FALSE)) 
list2 <- data.frame(x = c("bye","hello"), y = c(5, 8), z = c(FALSE, FALSE)) 

Select all data frames

lists <- mget(ls(pattern = "list"))

$list1
      x y     z
1 hello 1  TRUE
2   bye 4 FALSE

$list2
      x y     z
1   bye 5 FALSE
2 hello 8 FALSE

Combine them into one

do.call(rbind, lists) %>% 
  tibble()

# A tibble: 4 x 3
  x         y z    
  <chr> <dbl> <lgl>
1 hello     1 TRUE 
2 bye       4 FALSE
3 bye       5 FALSE
4 hello     8 FALSE
  • Related