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).
Using
dplyr
for this problem, as you've described it, is weird. You seem to want to work with vectors, not data.frames, anddplyr
functions expect data.frames in and return data.frames out, i.e. it's inputs and outputs are idempotent. For working with vectors, you should useouter
. Butdplyr
could be shoehorned into doing this task...Well you're using vectors of different length but maybe this will help if I understand correctly. I just made a dumby function with variable i
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 proposition
where
outer()
is much quicker