Search code examples
rfor-loopassign

Convert LIst To Dataframe Using For Loop And Saving Under Different Names In R


I am trying to convert my list consisting of 52 components to a dataframe for each of the components. Without using the for loop will look something like this which is tedious:

df1 = as.data.frame(list[1])
df2 = as.data.frame(list[2])
df3 = as.data.frame(list[3])
.
.
.
df50 = as.data.frame(list[50])

How do I achieve this using the for loop? My attempt:

for (i in seq_along(list)) {
  noquote(paste0("df", i)) = as.data.frame(list[i]) 
}

Error: target of assignment expands to non-language objec

I think I'll have to invovle assign.


Solution

  • If you have list of dataframes in list, you can name them and then use list2env to have them as separate dataframes in the environment.

    names(list) <- paste0('df', seq_along(list))
    list2env(list, .GlobalEnv)
    

    Using a reproducible exmaple,

    temp <- list(mtcars, mtcars)
    names(temp) <- paste0('df', seq_along(temp))
    list2env(temp, .GlobalEnv)
    
    
    head(df1)
    #                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
    #Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
    #Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
    #Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
    #Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
    #Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
    #Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1
    
    head(df2)
    #                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
    #Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
    #Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
    #Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
    #Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
    #Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
    #Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1
    

    However, note that

    • list is an internal function in R, so it is better to name your variables something else.
    • As @MrFlick suggested try to keep your data in a list as lists are easier to manage rather than creating numerous objects in your global environment.