[英]How to pass matrix columns as parameters to an .apply function?
I want to pass multiple parameters at once to a function, where these parameters are vectors contained in a matrix like this one: 我想一次将多个参数传递给一个函数,其中这些参数是包含在像这样的矩阵中的向量:
> head(M, 3)
[,1] [,2] [,3]
[1,] 1.3709584 1.304870 -0.3066386
[2,] -0.5646982 2.286645 -1.7813084
[3,] 0.3631284 -1.388861 -0.1719174
For example considering cor()
the following line gives me what I want, but I don't want nesting. 例如,考虑cor()
,下面的行给了我想要的东西,但我不想嵌套。
> sapply(1:3, function(x) sapply(1:3, function(y, ...) cor(M[, x], M[, y])))
[,1] [,2] [,3]
[1,] 1.0000000 -0.3749289 0.4400510
[2,] -0.3749289 1.0000000 -0.1533438
[3,] 0.4400510 -0.1533438 1.0000000
I thought outer()
would be a candidate, since: 我认为outer()
会成为候选者,因为:
> outer(1:3, 1:3, function(x, y) x + y)
[,1] [,2] [,3]
[1,] 2 3 4
[2,] 3 4 5
[3,] 4 5 6
But 但
corFun <- function(x, y) cor(M[, x], M[, y])
outer(1:3, 1:3, corFun)
won't work. 不行。 mapply(corFun, M[, 1], M[, 2])
attempts won't work either. mapply(corFun, M[, 1], M[, 2])
尝试也不起作用。
I want to do xFun(corFun, M, arg)
or even better xFun(cor, M, arg)
that gives (like above): 我想做xFun(corFun, M, arg)
甚至更好的xFun(cor, M, arg)
给出(如上所述):
[,1] [,2] [,3]
[1,] 1.0000000 -0.3749289 0.4400510
[2,] -0.3749289 1.0000000 -0.1533438
[3,] 0.4400510 -0.1533438 1.0000000
where arg <- combn(1:3, 2)
or arg <- t(expand.grid(1:3, 1:3))
. 其中arg <- combn(1:3, 2)
或arg <- t(expand.grid(1:3, 1:3))
。
Generally I'm wondering if there's an existing base R function something like xFun(FUN, ..., arg)
that passes a parameter matrix arg
with dim(arg)[1] == 2
column-wise to a function FUN = function(x, y)
, or, perhaps, even more generally dim(arg)[1] == length(formals(FUN))
. 一般来说,我想知道是否存在类似xFun(FUN, ..., arg)
的现有基本R函数, xFun(FUN, ..., arg)
带有dim(arg)[1] == 2
列参数的参数矩阵arg
传递给函数FUN = function(x, y)
,或者,更一般地说, dim(arg)[1] == length(formals(FUN))
。
Data: 数据:
set.seed(42)
M <- matrix(rnorm(30), 10, 3)
outer
is your function but you just need to Vectorize
your corfun
outer
是你的功能,但你只需要Vectorize
你的corfun
outer(1:3, 1:3, Vectorize(corFun))
# [,1] [,2] [,3]
#[1,] 1.0000000 -0.3749289 0.4400510
#[2,] -0.3749289 1.0000000 -0.1533438
#[3,] 0.4400510 -0.1533438 1.0000000
Another option would be combn
另一个选择是combn
combn(1:3, m = 3, FUN = corFun)[,, 1]
# [,1] [,2] [,3]
#[1,] 1.0000000 -0.3749289 0.4400510
#[2,] -0.3749289 1.0000000 -0.1533438
#[3,] 0.4400510 -0.1533438 1.0000000
The result however is an array, hence the [,, 1]
. 结果是一个数组,因此[,, 1]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.