Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unlist a list file to multiple dataframes [duplicate]

Tags:

dataframe

r

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?

like image 698
David Z Avatar asked Jan 09 '14 14:01

David Z


3 Answers

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.frames!. What are you trying to do.

like image 83
Simon O'Hanlon Avatar answered Oct 24 '22 07:10

Simon O'Hanlon


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.

like image 25
James Avatar answered Oct 24 '22 06:10

James


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.

like image 2
Tyler Rinker Avatar answered Oct 24 '22 06:10

Tyler Rinker