不在apply中传递所有可选参数

Pie*_*rre 9 r function

我在使用apply函数时遇到一些问题,在不需要时将参数传递给函数.我知道apply不知道如何处理可选参数,只是在函数上传递它们.

但无论如何,这就是我想做的事情:

首先,我想指定一个我想要使用的函数列表.

functions <- list(length, sum)
Run Code Online (Sandbox Code Playgroud)

然后我想创建一个在数据集上应用这些指定函数的函数.

myFunc <- function(data, functions) {
  for (i in 1:length(functions)) print(apply(X=data, MARGIN=2, FUN=functions[[i]]))
}
Run Code Online (Sandbox Code Playgroud)

这很好用.

data <- cbind(rnorm(100), rnorm(100))
myFunc(data, functions)

[1] 100 100
[1] -0.5758939 -5.1311173
Run Code Online (Sandbox Code Playgroud)

但我还想为一些函数使用额外的参数,例如

power <- function(x, p) x^p 
Run Code Online (Sandbox Code Playgroud)

哪个不能按我的意愿工作.如果我修改myFunc为:

myFunc <- function(data, functions, ...) {
  for (i in 1:length(functions)) print(apply(X=data, MARGIN=2, FUN=functions[[i]], ...))
}
Run Code Online (Sandbox Code Playgroud)

functions

functions <- list(length, sum, power)
Run Code Online (Sandbox Code Playgroud)

然后尝试我得到的功能

myFunc(data, functions, p=2)

Error in FUN(newX[, i], ...) : 
  2 arguments passed to 'length' which requires 1
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

抱歉,文字墙.谢谢!

Col*_*vel 4

您可以使用Curryfromfunctional来修复所需的参数,将函数放入要应用的函数列表中,最后迭代此函数列表:

library(functional)

power <- function(x, p) x^p 
funcs = list(length, sum, Curry(power, p=2), Curry(power, p=3))
lapply(funcs, function(f) apply(data, 2 , f))
Run Code Online (Sandbox Code Playgroud)

通过您的代码,您可以使用:

functions <- list(length, sum, Curry(power, p=2))
myFunc(data, functions)
Run Code Online (Sandbox Code Playgroud)