I have a list like this:
df_list <- list(
df1 = data.frame(A = 1:3, B = 4:6),
df2 = data.frame(A = 7:9, B = 10:12),
df3 = data.frame(A = 13:15, C = 16:18),
df4 = data.frame(A = 19:21, B = 22:24, C = 25:27)
)
For all data frames in this list that have the same number of columns AND the same column names, I want to put them into a separate list (e.g. list_1, list_2, list_3…).
Does anyone know if there is a quick way to do this?
3
Create a function to do this.
split_list <- function(lst) {
res <- lapply(unique(lapply(lst, names)), (x) {
lapply(lst, (y) y[identical(names(y), x)]) })
for(i in 1:length(res)) {
assign(paste("list", i, sep="_"), res[[i]]
[sapply(res[[i]], (x) ncol(x)>0)], .GlobalEnv)
}
}
Then call this function to create the separate lists in the environment.
split_list(df_list)
list_1
$df1
A B
1 1 4
2 2 5
3 3 6
$df2
A B
1 7 10
2 8 11
3 9 12
list_2
$df3
A C
1 13 16
2 14 17
3 15 18
list_3
$df4
A B C
1 19 22 25
2 20 23 26
3 21 24 27
4