将函数族应用于具有多个参数的函数 [英] Apply family of functions for functions with multiple arguments
问题描述
我想使用 apply 系列(在 R 中)中的一个函数来将具有两个参数的函数应用于两个矩阵.我认为这是可能的.我对么?否则,我似乎必须将两个矩阵合二为一,并根据新矩阵重新定义我的函数.
I would like to use a function from the apply family (in R) to apply a function of two arguments to two matrices. I assume this is possible. Am I correct? Otherwise, it would seem that I have to put the two matrices into one, and redefine my function in terms of the new matrix.
这是我想做的一个例子:
Here's an example of what I'd like to do:
a <- matrix(1:6,nrow = 3,ncol = 2)
b <- matrix(7:12,nrow = 3,ncol = 2)
foo <- function(vec1,vec2){
d <- sample(vec1,1)
f <- sample(vec2,1)
result <- c(d,f)
return(result)
}
我想将 foo
应用到 a
和 b
.
I would like to apply foo
to a
and b
.
推荐答案
(严格回答问题,而不是为您提供更好的方法供您在此处特别使用....)
(Strictly answering the question, not pointing you to a better approach for you particular use here....)
mapply
是 *apply
函数系列中的函数,用于在循环多个参数时应用函数.
mapply
is the function from the *apply
family of functions for applying a function while looping through multiple arguments.
因此,您在这里要做的是将每个矩阵转换为包含其行或列的向量列表(您没有指定).有很多方法可以做到这一点,我喜欢使用以下功能:
So what you want to do here is turn each of your matrices into a list of vectors that hold its rows or columns (you did not specify). There are many ways to do that, I like to use the following function:
split.array.along <- function(X, MARGIN) {
require(abind)
lapply(seq_len(dim(X)[MARGIN]), asub, x = X, dims = MARGIN)
}
然后你所要做的就是运行:
Then all you have to do is run:
mapply(foo, split.array.along(a, 1),
split.array.along(b, 1))
与 sapply
一样,mapply
会尽可能将您的输出放入数组中.如果您更喜欢输出为列表,请将 SIMPLIFY = FALSE
添加到 mapply
调用,或者等效地,使用 Map 函数:
Like sapply
, mapply
tries to put your output into an array if possible. If instead you prefer the output to be a list, add SIMPLIFY = FALSE
to the mapply
call, or equivalently, use the Map function:
Map(foo, split.array.along(a, 1),
split.array.along(b, 1))
这篇关于将函数族应用于具有多个参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!