【发布时间】:2016-07-01 07:22:13
【问题描述】:
我想将rollapply 函数与width、by 和FUN 参数的各种组合一起使用(width 和by 应该具有相同的值)。我启发了here 并创建了以下代码,这些代码正在运行,但到目前为止它与rollapply 无关,它只是演示了如何将几个参数传递给apply 内部的函数:
> dframe <- expand.grid(c(1,2,3), c(1,2,3))
> testFunc <- function(a, b) a^2 + b
> apply(dframe, 1, function(x) testFunc(x[1], x[2]))
[1] 2 5 10 3 6 11 4 7 12
> apply(dframe, 1, function(x) x[1]^2 + x[2])
[1] 2 5 10 3 6 11 4 7 12
> apply(dframe, 1, function(x) (x[1]^2 + x[2]))
[1] 2 5 10 3 6 11 4 7 12
> apply(dframe, 1, function(x) {x[1]^2 + x[2]})
[1] 2 5 10 3 6 11 4 7 12
我的最终解决方案在这里,但这不起作用:
> dframe <- expand.grid(c(1,2,3), c(median, mean))
> testFunc <- function(a, b) rollapply(mtcars, width = a, by = a, FUN = b, align="left")
> apply(dframe, 1, function(x) testFunc(x[1], x[2]))
Error in get(as.character(FUN), mode = "function", envir = envir) :
object 'b' of mode 'function' was not found
> apply(dframe, 1, function(x) rollapply(mtcars, width = x[1], by = x[1], FUN = x[2], align="left"))
Error in match.fun(FUN) : 'x[2]' is not a function, character or symbol
当我直接调用testFunc 时,一切正常,所以我猜问题是apply 无法以某种方式收集结果:
> testFunc(10,mean)
mpg cyl disp hp drat wt qsec vs am gear carb
[1,] 20.37 5.8 208.61 122.8 3.538 3.1280 18.581 0.6 0.3 3.6 2.5
[2,] 19.89 6.6 259.25 149.6 3.552 3.6689 18.301 0.4 0.3 3.4 2.9
[3,] 20.39 6.2 228.25 152.6 3.654 2.8633 16.914 0.3 0.5 3.9 2.6
> class(testFunc(10,mean))
[1] "matrix"
我也试过调试testFunc 并从apply 调用它,似乎参数传递正确:
> debug(testFunc)
> apply(dframe, 1, function(x) testFunc(x[1], x[2]))
debugging in: testFunc(x[1], x[2])
debug: rollapply(mtcars, width = a, by = a, FUN = b, align = "left")
Browse[2]> print(a)
$Var1
[1] 1
Browse[2]> print(b)
$Var2
function (x, na.rm = FALSE)
UseMethod("median")
<bytecode: 0x08244ffc>
<environment: namespace:stats>
Browse[2]> n
Error in get(as.character(FUN), mode = "function", envir = envir) :
object 'b' of mode 'function' was not found
问题:
- 什么是错误,我做错了什么?
- 如何用
expand.grid替换嵌套循环并调用内部 具有多个参数的函数? - 如何使用
*apply系列函数返回矩阵列表?
PS:我想使用两个嵌套循环很容易实现这一点,但我想知道是否有 R-way。
PPS:Here 是关于类似错误(object 'b' of mode 'function' was not found)的答案,结论是b(在我的情况下)与命名参数与其他函数冲突。但我在我的代码中看不到这个问题。
【问题讨论】:
标签: r