R: apply a function to every element of two variables respectively

adam.888 picture adam.888 · Feb 12, 2016 · Viewed 17.2k times · Source

I have a function with two variables x and y:

fun1 <- function(x,y) {
  z <- x+y
  return(z)
}

The function work fine by itself:

fun1(15,20)

But when I try to use it with two vectors for x and y with an apply function I do not get the correct 56*121 array

Lx  <- c(1:56)
Ly <- c(1:121)

mapply(fun1, Lx, Ly)

I would be grateful for your help and also on advice on the fastest solution (eg is a data.table or dplyr solution faster than apply).

Answer

HubertL picture HubertL · Feb 12, 2016

If you want to use mapply() you have to provide it with n lists of arguments that have same size, and that will be passed to the function n by n, as in:

mapply(fun1,c(1,2,3), c(4, 5, 6))
[1] 5 7 9

or one argument can be a scalar as in:

mapply(fun1,c(1,2,3), 4)
[1] 5 6 7

Since you're trying to use all combinations of Lx and Ly, you can iterate one list, then iterate the other, like:

sapply(Lx, function(x) mapply(fun1,x,Ly))

or

sapply(Ly, function(y) mapply(fun1,Lx,y))

which produces same result as rawr proposition

outer(Lx, Ly, fun1)

where outer() is much quicker