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))
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With