【问题标题】:How to save forloop() with different names in R如何在 R 中保存具有不同名称的 for loop()
【发布时间】:2021-08-31 01:09:39
【问题描述】:

我有一个函数和一个for循环,我想将相同的for循环迭代3次for(i in 1:3){}并将for循环输出保存为具有不同名称的列表,例如df.1df.2df.3。非常感谢。

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

预期的答案

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 

【问题讨论】:

    标签: r for-loop data-manipulation nested-for-loop


    【解决方案1】:

    for 循环代码放入函数中,并使用replicate 重复代码n 次-

    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 将拥有数据框列表。

    如果您希望它们作为单独的数据框命名列表并使用list2env

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-16
      • 2016-02-04
      • 1970-01-01
      • 2018-07-03
      • 2018-08-15
      • 1970-01-01
      • 2021-06-18
      • 1970-01-01
      相关资源
      最近更新 更多