【问题标题】:how to run different functions in forloop如何在for循环中运行不同的函数
【发布时间】:2021-08-31 01:48:40
【问题描述】:

我想在同一个循环中运行两个不同的函数,并使用特定名称 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-loop nested-loops data-manipulation


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2013-04-21
      • 1970-01-01
      • 2011-01-31
      • 1970-01-01
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-01
      相关资源
      最近更新 更多