Search code examples
rfor-loopdata-manipulationnested-for-loop

How to save forloop() with different names in R


I have a function and a for-loop, I would like to iterate the same for-loop to 3 times for(i in 1:3){} and save the for loop output as a list with different names such as df.1, df.2, and df.3. Many thanks in advance.

df <- tibble( a = rnorm(10),b = rnorm(10))

rescale01 <- function(x) {
  rng <- range(x, na.rm = TRUE)
  (x - rng[1]) / (rng[2] - rng[1])
}

for (i in seq_along(df)) {
  df[[i]] <- rescale01(df[[i]])
}
df

Expected Answer

DF.1
 A tibble: 10 x 2
        a      b
    <dbl>  <dbl>
 1 1      0.624 
 2 0      0.421 
 3 0.551  1     
 4 0.320  0.466 
 5 0.266  0.247 
 6 0.0261 0.103 
 7 0.127  0.519 
 8 0.588  0.0623
 9 0.489  0     
10 0.556  0.540 


DF.2
 A tibble: 10 x 2
        a      b
    <dbl>  <dbl>
 1 1      0.624 
 2 0      0.421 
 3 0.551  1     
 4 0.320  0.466 
 5 0.266  0.247 
 6 0.0261 0.103 
 7 0.127  0.519 
 8 0.588  0.0623
 9 0.489  0     
10 0.556  0.540 


DF.3
 A tibble: 10 x 2
        a      b
    <dbl>  <dbl>
 1 1      0.624 
 2 0      0.421 
 3 0.551  1     
 4 0.320  0.466 
 5 0.266  0.247 
 6 0.0261 0.103 
 7 0.127  0.519 
 8 0.588  0.0623
 9 0.489  0     
10 0.556  0.540 

Solution

  • Put the for loop code in a function and repeat the code for n times using replicate -

    apply_fun <- function(df) {
      for (i in seq_along(df)) {
        df[[i]] <- rescale01(df[[i]])
      }
      df
    }
    result <- replicate(3, apply_fun(df), simplify = FALSE)
    

    result will have list of dataframes.

    If you want them as separate dataframes name the list and use list2env.

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