mnal
mnal

Reputation: 85

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.

I'm looking for a way to basically do the R equivalent of the c program

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. How can I pass all pairwise combinations of the vectors 1:12 and 1:9 into func?

Upvotes: 0

Views: 1188

Answers (2)

Gwang-Jin Kim
Gwang-Jin Kim

Reputation: 9865

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. t transposes the result, and I take it as a data.frame (t returns annoyingly a matrix ... even when applied on data.frames ...) and sapply over it. 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. These actual row-vectors are taken from the function and the function func applied on the two values produce. So at the end, we took every pairwise combinations possible and entered it to function(v) ...

Upvotes: 0

Zheyuan Li
Zheyuan Li

Reputation: 73285

Does this work: outer(1:12, 1:9, func)?

If not, use 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`

Upvotes: 1

Related Questions