I have a function
myfunction <- function(x,y){
x y
}
and I want to pass x and y vectors to it and get a vector of their same length which is just the sum of their elements.
For some reason when I use
sapply(x,myfunction,y)
I get a matrix instead of a vector. What am I doing wrong? Am I using the wrong function?
Example:
x = c(1,2,3,4)
y = c(2,4,6,8)
sapply(x,myfunction,y)
> [,1] [,2] [,3] [,4]
[1,] 3 4 5 6
[2,] 5 6 7 8
[3,] 7 8 9 10
[4,] 9 10 11 12
when my desired output is a vector (3,6,9,12).
CodePudding user response:
Arithmetic operations are vectorized, so the function can be applied directly
myfunction(x, y)
[1] 3 6 9 12
With sapply
, the X
input argument is used by x
thus, each element of x
is looped while the y
remains the whole vector, thus when we apply the function, it returns the output with the same length as 'y' for each element of 'x' and also as sapply
use simplify = TRUE
by default, it returns a matrix. If we need to use *apply function (and assuming the example is a simplified case), then we may need either mapply
or Map
which does loop over the corresponding elements of both inputs and apply the function on each element separately
mapply(myfunction, x, y)
[1] 3 6 9 12