Search code examples
rmapply

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?


Solution

  • 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`