Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List elements to dataframes in R

Tags:

r

How would I go about taking elements of a list and making them into dataframes, with each dataframe name consistent with the list element name?

Ex:

exlist <- list(west=c(2,3,4), north=c(2,5,6), east=c(2,4,7))

Where I'm tripping up is in the actual naming of the unique dataframes -- I can't figure out how to do this with a for() loop or with lapply:

for(i in exlist) {
    i <- data.frame(exlist$i)
}

gives me an empty dataframe called i, whereas I'd expect three dataframes to be made (one called west, another called north, and another called east)

When I use lapply syntax and call the individual list element name, I get empty dataframes:

lapply(exlist, function(list) i <- data.frame(list["i"]))

yields

data frame with 0 columns and 0 rows
> $west
  list..i..
1        NA

$north
  list..i..
1        NA

$east
  list..i..
1        NA
like image 812
Marc Tulla Avatar asked Sep 30 '22 14:09

Marc Tulla


1 Answers

If you want to convert your list elements to data.frames, you can try either

lapply(exlist, as.data.frame)

Or (as suggested by @Richard), depends on your desired output:

lapply(exlist, as.data.frame.list)

It is always recommended to keep multiple data frames in a list rather than polluting your global environment, but if you insist on doing this, you could use list2env (don't do this), such as:

list2env(lapply(exlist, as.data.frame.list), .GlobalEnv)
like image 112
David Arenburg Avatar answered Oct 02 '22 14:10

David Arenburg