Michael Michael - 11 months ago 40
R Question

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

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.

Answer Source

No need for apply:

#define function
myfunc <- function(var1, var2, var3){
  result <- var1*var2*var3
#dummy data
dat <- data.frame(A=c(1,2,3),B=c(4,5,6),C=c(7,8,9))

#test function

[1]  28  80 162
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download