Reputation: 72994
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.
> 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(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.
I want to do xFun(corFun, M, arg)
or even better xFun(cor, M, arg)
that gives (like above):
[,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))
.
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))
.
Data:
set.seed(42)
M <- matrix(rnorm(30), 10, 3)
Upvotes: 2
Views: 280
Reputation: 26343
Another option would be 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]
.
Upvotes: 3
Reputation: 389055
outer
is your function but you just need to Vectorize
your 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
Upvotes: 4