Convert a list with different line dataframes into independent dataframes

Asked

Viewed 96 times

5

I have a list with 3 dataframes, which derive from the function split:

> 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 transform each of these groups into independent dataframes. I tried a few functions, but was unsuccessful. In one of them, for example, appeared the following message:

Arguments imply differing number of Rows: 3, 4

2 answers

3


Despite the function createdf from @Daniel work well, the base R already has a function that makes it, the function list2env.

Creating the same list a in a new R session:

ls()
#character(0)

Now the list is created a.

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"

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, simply add the environment global for variables to be exported from the function.

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

createdf(a)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.