【问题标题】:Combinatorics for functions in R, applying every p length combination of n functionsR中函数的组合,应用n个函数的每个p长度组合
【发布时间】:2016-01-18 23:27:19
【问题描述】:

所以我有 n 个函数,它们都在同一个向量上运行,假设命名为 x。例如,它们可能是:

s1 = function(x) mean(x)
s2 = function(x) sd(x)
...
sn = function(x) 1/length(x)*sum(x^3)
x <- c(3, 1, 5, 2, 7, 2, 4, 2, 1)

我想生成 p 个这些函数的所有可能组合,并将每个组合应用于向量 x。

到目前为止,我得到的是 combn 函数,但它似乎只适用于这样的字符向量:

a <- c("s1", "s2", "s3", ..., "sn")
b <- combn(a, 2)
b
     [,1] [,2] [,3] ...
[1,] "s1" "s1" "s2" ...
[2,] "s2" "s3" "s3" ...

我需要一种方法来轻松地制作我所有函数名称的向量,以及一种获取上面 b 列并将所有函数一起应用的方法。 我知道 plyr 中的每个函数,它可以完美地工作,除了 combn 的输出是一个字符向量并且每个函数都需要实际函数作为参数,而不是名称。所以我需要的第二件事是一种转换方式

each("s1", "s2")

进入

each(s1, s2)

其中顶部是 b 矩阵的一列,第二个使用我在开始时定义的函数。

理想情况下,最终代码将使用 apply 函数应用于 b 的每一列。

非常欢迎任何关于我无法弄清楚的部分的帮助或关于另一种方法的想法。

【问题讨论】:

    标签: r combinatorics


    【解决方案1】:

    如何将函数存储在列表中:

    funs <- list(
      mean
      , max
      , function(x) 1)
    

    那么,设数据向量为:

    set.seed(202)
    z <- runif(100)
    

    为了得到你想要的结果,你可以这样应用它们:

    combn(
      length(funs)
      , 2
      , FUN = function(x) {
        lapply(
          # select the functions from the list that correspond to the combination
          funs[x]
          # apply each function in the list "fx" to the data vector
          , function(fx) fx(z)
        )
      }
    )
    

    结果如下:

         [,1]      [,2]      [,3]     
    [1,] 0.4971414 0.4971414 0.9969858
    [2,] 0.9969858 1         1    
    

    【讨论】:

      【解决方案2】:

      你可以跳过 string-> 函数查找,只需制作一个函数矩阵。然后apply(b, 1:2)依次对每个函数求值:

      > x <- c(3, 1, 5, 2, 7, 2, 4, 2, 1)
      > a <- c(sum, mean, sd)
      > b <- combn(a,2)
      > str(b)
      List of 6
       $ :function (..., na.rm = FALSE)  
       $ :function (x, ...)  
       $ :function (..., na.rm = FALSE)  
       $ :function (x, na.rm = FALSE)  
       $ :function (x, ...)  
       $ :function (x, na.rm = FALSE)  
       - attr(*, "dim")= int [1:2] 2 3        
      > apply(b, 1:2, function(f) f[[1]](x))
           [,1] [,2] [,3]
      [1,]   27   27    3
      [2,]    3    2    2
      

      【讨论】:

        【解决方案3】:

        为了回答这个问题(而不是建议替代工作流程),我们可以通过封装会话的环境按名称访问变量(例如函数)。环境的使用与 R 中的其他结构类似,例如列表和数据框。

        函数environment可以用来获取当前环境。全局环境也可通过.GlobalEnv 获得(使用?environment 获取更多信息)。以下是通过函数名称作为字符串访问函数的示例:

        > f <- function(x) 2 * x
        > g <- function(x) x^2
        > h <- function(x) 1 / x
        > for (fun in c("f", "g", "h")) 
        + print(sprintf("%s(3) = %s", fun, environment()[[fun]](3)))
        [1] "f(3) = 6"
        [1] "g(3) = 9"
        [1] "h(3) = 0.333333333333333" 
        

        有关 R 环境的更多信息,请查看Wickham's Advanced R tutorial on environments

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-03-01
          • 1970-01-01
          • 2019-05-10
          • 1970-01-01
          • 2019-07-13
          • 1970-01-01
          • 2019-03-11
          相关资源
          最近更新 更多