Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bind rows on list of elements to list of data.frame

Tags:

r

I have list of R elements and want to bind row all elements within the list. Each row binds to data.frame based on the column class. The actual data is quite large and each class has different columns. Here is sample

df_list <- list()
df_list[[1]] <- data.frame(Class = "x", y = 1, stringsAsFactors = F)
df_list[[2]] <- data.frame(Class = "x", y = 2, stringsAsFactors = F)
df_list[[3]] <- data.frame(Class = "a", y = 3, stringsAsFactors = F)
df_list[[4]] <- data.frame(Class = "x", y = 4, stringsAsFactors = F)
df_list[[5]] <- data.frame(Class = "a", y = 5, stringsAsFactors = F)

Desired output, looking this to be done programmatically

df_list_out <- list()

df_list_out[[1]] <- bind_rows(data.frame(Class = "x", y = 1, 
                                         stringsAsFactors = F),
                              data.frame(Class = "x", y = 2, 
                                          stringsAsFactors = F),
                              data.frame(Class = "x", y = 4, 
                                           stringsAsFactors = F))


df_list_out[[2]] <- bind_rows(data.frame(Class = "a", y = 3, 
                                           stringsAsFactors = F),
                              data.frame(Class = "a", y = 5, 
                                         stringsAsFactors = F))
like image 290
Kg211 Avatar asked Sep 16 '25 07:09

Kg211


1 Answers

One way would be to rbind the list of dataframes together and then split

temp <- do.call(rbind, df_list)
split(temp, temp$Class)

#$a
#  Class y
#3     a 3
#5     a 5

#$x
#  Class y
#1     x 1
#2     x 2
#4     x 4

In dplyr, we can do

library(dplyr)

df_list %>% bind_rows() %>% group_split(Class) 
like image 149
Ronak Shah Avatar answered Sep 17 '25 21:09

Ronak Shah