I have these lists in the global environment:
list_1 <- list(data.frame(A = 1:3, B = 4:6), data.frame(A = 7:9, B = 10:12))
list_2 <- list(data.frame(X = 1:2, Y = 3:4), data.frame(X = 5:6, Y = 7:8))
list_3 <- list(data.frame(M = 1:4, N = 5:8), data.frame(M = 9:12, N = 13:16))
I would like to turn each of these lists into a dataframe, e.g. here is how I would have done this manually:
list_1 = do.call(rbind.data.frame, list_1)
list_2 = do.call(rbind.data.frame, list_2)
list_3 = do.call(rbind.data.frame, list_3)
Is it possible to do this with a for loop? Normally in a for loop, I store the output of each iteration to a list itself, whereas this time I want to make individual data frames.
You can try
list2env(
lapply(
mget(ls(pattern = "^list_\\d+")),
\(x) do.call(rbind, x)
),
envir = .GlobalEnv
)
and you can check
> mget(ls(pattern = "^list_\\d+"))
$list_1
A B
1 1 4
2 2 5
3 3 6
4 7 10
5 8 11
6 9 12
$list_2
X Y
1 1 3
2 2 4
3 5 7
4 6 8
$list_3
M N
1 1 5
2 2 6
3 3 7
4 4 8
5 9 13
6 10 14
7 11 15
8 12 16