Apply Function Using Multiple Changing Arguments in R
Solution 1
No need for apply
:
#define function
myfunc <- function(var1, var2, var3){
result <- var1*var2*var3
return(result)
}
#dummy data
dat <- data.frame(A=c(1,2,3),B=c(4,5,6),C=c(7,8,9))
#test function
myfunc(dat$A,dat$B,dat$C)
#output
[1] 28 80 162
Solution 2
You seem to be fairly close, but you're missing a little bit in the call.
apply(data, 1, function(x,y,z) myfunc(data$var1,data$var2,data$var3))
seems to do the trick.
edit: I tested this on the data set
data<-data.frame(a=c(1,2,3),b=c(4,5,6),c=c(7,8,9))
and got the output
[,1] [,2] [,3]
[1,] 28 28 28
[2,] 80 80 80
[3,] 162 162 162
Solution 3
Here is an untested (no reproducible example provided) suggestion:
myfunc <- function(x)){
result <- x$var1*x$var2*x$var3
return(result)
}
apply(data, 1, myfunc)
Related videos on Youtube
Michael
Updated on July 18, 2020Comments
-
Michael almost 4 years
I want to apply a function over all rows referencing multiple columns in a data frame in R. So, for example, if I have a data frame called "data" with three variables "var1", "var2", and "var3" and I want to apply a function to each row:
myfunc <- function(var1, var2, var3)){ result <- var1*var2*var3 return(result) }
Then the pseudocode would be:
apply(data, myfunc(data$var1, data$var2, data$var3))
This code does not work, however, because data is a data frame, not a vector, and lapply does not seem able to take more than one vector. How do I make this work? I am open to any type of solution, but I have to be able to reference multiple changing arguments and call a predefined function.
-
QuantIbex almost 11 yearsAs pointed out by @zx8754 in his answer, you might avoid the use of apply. But this will be possible only if the computation in the function is vectorized, which is the case in the example you provided. Is it the case with the computation you want to do (
myfunc
seems to be for illustration purpose only)?
-