Convert a list with dataframes of different rows into independent dataframes [R]

5

I have a list of 3 dataframes, which are derived from the split function:

> split
$'1'
bin group1 group2 missing score1 score2 gender size score3   income          city
  0      1      1      NA      3      2      M    S      4 1605.525 San Francisco
  0      1      2       5      4      4      M    S      5 3463.773  Santa Monica
  0      1      1      NA      4      5      M    L      4 2241.497  Santa Monica

$'2'
bin group1 group2 missing score1 score2 gender size score3   income         city
  1      2      2       7      7      4      M    S      3 2575.955 Santa Monica
  1      2      1       6      6      5      F    L      3 3004.282    Hollywood
  0      2      2      NA      4      6      F    S      2 3458.309    Hollywood

$'3'
bin group1 group2 missing score1 score2 gender size score3   income         city
  0      3      2       4      2      3      M    L      5 1957.105 Santa Monica
  0      3      1      NA      3      6      F    L      3 1786.686    Hollywood
  1      3      2       4      6      7      F    S      4 2065.093    Hollywood
  1      3      1       5      7      8      F    L      7 1561.554    Hollywood

My goal is, with ONE function, to turn each of these groups into independent dataframes. I tried some functions, but I did not succeed. In one of them, for example, the following message appeared:

arguments imply differing number of rows: 3, 4

    
asked by anonymous 21.08.2018 / 03:35

2 answers

3

Although the createdf function of @Daniel works fine, the base R already has a function that does this, the list2env function.

Creating the same list a in a new R session:

ls()
#character(0)

The a list is now created.

a <- list(cars = cars, mtcars = mtcars, CO2 = CO2)
ls()
#[1] "a"

And turn each of these list members into independent dataframes.

list2env(a, envir = .GlobalEnv)
#<environment: R_GlobalEnv>

ls()
#[1] "a"      "cars"   "CO2"    "mtcars"
    
21.08.2018 / 16:09
2

You can generate your dataframes from a for.

a <- list(cars = cars, mtcars = mtcars, CO2 = CO2)

for(i in 1:length(a)) { 
  assign(labels(a)[i] , a[[i]])
}

To create as a function, just add the environment global so that the variables are exported from the function.

createdf <- function(a){
  for(i in 1:length(a)) { 
    assign(labels(a)[i] , a[[i]], , envir = .GlobalEnv)
  } 
}

createdf(a)
    
21.08.2018 / 15:06