Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply Function Using Multiple Changing Arguments in R

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.

like image 531
Michael Avatar asked Jul 18 '26 10:07

Michael


1 Answers

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
like image 185
yawgeh Avatar answered Jul 21 '26 00:07

yawgeh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!