【问题标题】:R: Evaluate function for multiple and differently-changing argumentsR:为多个不同变化的参数评估函数
【发布时间】:2020-12-13 00:05:04
【问题描述】:

我有一个有 4 个参数的函数:

    my.function <- function(w,x,y,z){
       w + x + y + z
    }

我可以给这个函数多个z的值:

> my.function(1,1,1,1:5)
[1] 4 5 6 7 8

但是,如果我想给出w,x,y 的值的函数列表和z 的值向量,这样该函数将使用z 的每个元素评估wxy.args 的每个set ?

wxy.args <- list(set1 = list(w = 1.1, x = 2.1, y = 3.1),
                 set2 = list(w = 1.2, x = 2.2, y = 3.3),
                 set3 = list(w = 1.3, x = 2.3, y = 3.3))
z <- 1:5

理想情况下,我希望得到一个n x m 矩阵,其中n = setm = z。因此,我想使用outer()but it doesn't seem like that is possible

所以,我想这将涉及 apply family 之一或 apply 和 do.call 的某种组合,但我正在努力解决它。

提前致谢!

【问题讨论】:

    标签: r function apply do.call


    【解决方案1】:

    您可以使用mapply 来迭代您的集合。它遍历列表元素。我使用do.call 将子列表传递给my.function

    mapply(function(...) do.call(my.function, c(list(z = z), ...)), 
       wxy.args)
    #     set1 set2 set3
    #[1,]  7.3  7.7  7.9
    #[2,]  8.3  8.7  8.9
    #[3,]  9.3  9.7  9.9
    #[4,] 10.3 10.7 10.9
    #[5,] 11.3 11.7 11.9
    

    如有必要,使用t 转置矩阵。

    【讨论】:

    • 太好了,这就是我所希望的。如果wxy.args 中的集合列表是另一个列表的元素,你能告诉我为什么它不起作用吗?
    • 如果它是另一个列表的元素,只需从该列表中提取它?
    【解决方案2】:

    一个选项可能是:

    sapply(z, function(x) lapply(wxy.args, function(y) sum(unlist(y), x)))
    
         [,1] [,2] [,3] [,4] [,5]
    set1 7.3  8.3  9.3  10.3 11.3
    set2 7.7  8.7  9.7  10.7 11.7
    set3 7.9  8.9  9.9  10.9 11.9
    

    【讨论】:

      【解决方案3】:
      library(purrr)
      
      wxy.args %>% map(~c(.x, z = list(z))) %>%
        map(~do.call("my.function", args = .x)) %>%
        unlist() %>%
        matrix(nrow = length(wxy.args), byrow = TRUE)
      

      给予:

           [,1] [,2] [,3] [,4] [,5]
      [1,]  7.3  8.3  9.3 10.3 11.3
      [2,]  7.7  8.7  9.7 10.7 11.7
      [3,]  7.9  8.9  9.9 10.9 11.9
      

      【讨论】:

        【解决方案4】:

        要使用outer 定义my.function2,这是my.function 的一个版本,它将zwxy 作为两个单独的参数,然后将它的矢量化版本传递给outer

        my.function2 <- function(z, wxy) do.call(my.function, c(wxy, z))
        outer(z, wxy.args, Vectorize(my.function2))
        

        给予:

             set1 set2 set3
        [1,]  7.3  7.7  7.9
        [2,]  8.3  8.7  8.9
        [3,]  9.3  9.7  9.9
        [4,] 10.3 10.7 10.9
        [5,] 11.3 11.7 11.9
        

        另一个更简单但稍微乏味的等效可能性是使用此版本的my.function2 将参数写出my.function

        my.function2 <- function(z, wxy) my.function(wxy[[1]], wxy[[2]], wxy[[3]], z)
        

        【讨论】:

          猜你喜欢
          • 2013-08-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-12-01
          • 1970-01-01
          • 2015-07-05
          • 2016-04-20
          • 2013-07-17
          相关资源
          最近更新 更多