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).
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:or one argument can be a scalar as in:
Since you're trying to use all combinations of
Lx
andLy
, you can iterate one list, then iterate the other, like:or
which produces same result as rawr's proposition in their comment above
where
outer()
is much quicker