Home > Enterprise >  save the list objects created in forloop with different names in R
save the list objects created in forloop with different names in R

Time:10-17

I would like to save all the list objects which are created by for loop as different datasets in the environment with their proper name for example gapminder_Asia, gapminder_Europe,..etc. Many thanks in advance.

library(gapminder)
cont <- unique(gapminder$continent)
df <- NULL
for(i in 1:(length(cont))) {
  temp <- gapminder[gapminder$continent == cont[i], ]
  colnames(temp) <- paste0(paste(cont[i]))
  df[[i]] <- temp
}

df

Expected Answer,

> unique(gapminder$continent)
[1] Asia     Europe   Africa   Americas Oceania 

head(gapminder_Asia) 

 1 Afghanistan Asia   1952  28.8  8425333  779.
 2 Afghanistan Asia   1957  30.3  9240934  821.
 3 Afghanistan Asia   1962  32.0 10267083  853.
 4 Afghanistan Asia   1967  34.0 11537966  836.
 5 Afghanistan Asia   1972  36.1 13079460  740.
 

CodePudding user response:

Personally I would prefer to keep the dataset inside a list using e.g. split but if your desired result is to have different named objects then you could do so via assign:

library(gapminder)

df <- split(gapminder, gapminder$continent)
for(i in names(df)) {
  assign(paste("gapminder", i, sep = "_"), df[[i]])
}

gapminder_Africa
#> # A tibble: 624 × 6
#>    country continent  year lifeExp      pop gdpPercap
#>    <fct>   <fct>     <int>   <dbl>    <int>     <dbl>
#>  1 Algeria Africa     1952    43.1  9279525     2449.
#>  2 Algeria Africa     1957    45.7 10270856     3014.
#>  3 Algeria Africa     1962    48.3 11000948     2551.
#>  4 Algeria Africa     1967    51.4 12760499     3247.
#>  5 Algeria Africa     1972    54.5 14760787     4183.
#>  6 Algeria Africa     1977    58.0 17152804     4910.
#>  7 Algeria Africa     1982    61.4 20033753     5745.
#>  8 Algeria Africa     1987    65.8 23254956     5681.
#>  9 Algeria Africa     1992    67.7 26298373     5023.
#> 10 Algeria Africa     1997    69.2 29072015     4797.
#> # … with 614 more rows

Created on 2021-10-16 by the reprex package (v2.0.1)

  • Related