如何在 FORLOOP 中运行不同的函数

how to run different functions in forloop

提问人:Seyma Kalay 提问时间:6/15/2021 更新时间:6/15/2021 访问量:28

问:

我想在同一个循环上运行两个不同的函数,并使用特定名称和 保存结果。提前非常感谢。df.rescale01df.rescale.02

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

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

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

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

预期答案

 rescale01
 A tibble: 10 x 2
       a     b
   <dbl> <dbl>
 1 0.354 0.627
 2 0.657 0.545
 3 0     0.397
 4 0.602 0    
 5 0.539 0.698
 6 0.775 1    
 7 1     0.216
 8 0.949 0.286
 9 0.782 0.244
10 0.239 0.523

 rescale02
A tibble: 10 x 2
        a      b
    <dbl>  <dbl>
 1   2.83   1.59
 2   1.52   1.83
 3 Inf      2.52
 4   1.66 Inf   
 5   1.85   1.43
 6   1.29   1   
 7   1      4.63
 8   1.05   3.49
 9   1.28   4.10
10   4.18   1.91
r for 嵌套循环 数据操作

评论


答:

1赞 KaptajnKasper 6/15/2021 #1

您可以将函数和结果存储在单独的列表中,如下所示

library(tidyverse)
set.seed(123)

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

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

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

rescale = list(rescale01 = rescale01, rescale02 = rescale02)
rslt = list()
for (i in seq_along(rescale)) {
  for (j in seq_along(df)) {
    df[[j]] <- rescale[[i]](df[[j]])
  }
  rslt[[names(rescale)[i]]] <- df
}
rslt

这将给出输出

> rslt
$rescale01
# A tibble: 10 x 2
       a     b
   <dbl> <dbl>
 1 0.236 0.850
 2 0.347 0.620
 3 0.948 0.631
 4 0.448 0.553
 5 0.468 0.376
 6 1     1    
 7 0.579 0.657
 8 0     0    
 9 0.194 0.711
10 0.275 0.398

$rescale02
# A tibble: 10 x 2
        a      b
    <dbl>  <dbl>
 1   4.23   1.18
 2   2.88   1.61
 3   1.06   1.59
 4   2.23   1.81
 5   2.14   2.66
 6   1      1   
 7   1.73   1.52
 8 Inf    Inf   
 9   5.15   1.41
10   3.64   2.51