[英]Apply a function over pairwise combinations of arguments
I'm not that familiar with R so this question may have already been answered but I just probably couldn't understand the answer so any links to other threads would be helpful. 我对R不太熟悉,所以可能已经回答了这个问题,但是我可能无法理解答案,因此与其他线程的任何链接都将有所帮助。
I'm looking for a way to basically do the R equivalent of the c program 我正在寻找一种方法来基本上做R相当于C程序
for(int i = 0; i < 12; i++){
for(int j = 0; j < 9; j++){
arr[i][j] = func(i+1,j+1);
}
}
I tried 我试过了
x <- mapply(func, 1:12, 1:9)
but it only passes (1,1), (2,2), (3,3) ... into func
. 但它只会将(1,1),(2,2),(3,3)...传递给
func
。 How can I pass all pairwise combinations of the vectors 1:12 and 1:9 into func
? 如何将向量1:12和1:9的所有成对组合传递到
func
?
Does this work: outer(1:12, 1:9, func)
? 这能工作吗
outer(1:12, 1:9, func)
?
If not, use matrix(apply(expand.grid(1:12, 1:9), 1, func), 12, 9)
. 如果不是,请使用
matrix(apply(expand.grid(1:12, 1:9), 1, func), 12, 9)
。
Background: "dims [product xx] do not match the length of object [xx]" error in using R function `outer` 背景: 使用R函数“外部”时出现“尺寸[产品xx]尺寸与对象[xx]的长度不匹配”错误
sapply(data.frame(t(expand.grid(1:12, 1:9))), function(v) func(v[1], v[2]))
expand.grid
creates all combinations as data frame rows. expand.grid
所有组合创建为数据框行。 t
transposes the result, and I take it as a data.frame
( t
returns annoyingly a matrix ... even when applied on data.frame
s ...) and sapply
over it. t
转置结果,然后将其作为data.frame
(即使应用到data.frame
s上, t
也会令人讨厌地返回矩阵...)并sapply
其上。 Since sapply
treats data frames like a list of column values, I get columnwise (actually rowwise - after application of t
transpose ...) listing of the data frame conent. 由于
sapply
像对待列值列表一样对待数据帧,因此我得到了按列列出(实际上是按行-在应用t
transpose ...之后)列出的数据帧。 These actual row-vectors are taken from the function and the function func
applied on the two values produce. 这些实际的行向量取自该函数,并且将函数
func
应用于两个值。 So at the end, we took every pairwise combinations possible and entered it to function(v) ... 因此,最后,我们尽可能采用了每对组合,并将其输入到function(v)...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.