I created a R list with 72 elements. How I unlist this file to 72 single dataframes with the name of each element?
Here is an example:
L <- list(data.frame(matrix(1:4,2,2)),
data.frame(matrix(9:12,2,2)),
data.frame(matrix(5:8,2,2)))
names(L)<-c("a","b","c")
How can I get three dataframes, a,b,and c?
There's a function for that...
list2env( L , .GlobalEnv )
But like James said, you need to have a good reason for not wanting to keep them in a list. It's much easier to work with lists than 72 separate data.frame
s!. What are you trying to do.
You can use assign
to the global environment within an lapply
. Note I have wrapped the call in invisible
to avoid printing the output to the console.
invisible(lapply(names(L),function(x) assign(x,L[[x]],.GlobalEnv)))
ls()
[1] "a" "b" "c" "L"
a
X1 X2
1 1 3
2 2 4
However, while the elements are in the list, they might be easier to work with, using lapply
for example.
This came to mind but James had already posted a better answer (essentially mine is the same but less cool) and then Simon and even better. Just for completeness I'll throw it up but heed their warnings:
for (i in seq_along(L)) {
assign(names(L)[i], L[[i]], .GlobalEnv)
}
EDIT
Based on Konrad's response I just realized you can do:
for (i in names(L)) {
assign(i, L[[i]], .GlobalEnv)
}
I didn't know for
loops could use non indices. Cool.
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