Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I apply a custom multi-variate function to each row of a data frame in R?

Suppose I have a data frame with columns named "foo" and "bar"

mydata <- data.frame(foo=rnorm(100), bar=rnorm(100))

and suppose I have a custom scalar function that expects scalar inputs "x" and "y" and produces a scalar output, for example

myfunction <- function(x, y) { if (x>0) y else x }

How do I apply myfunction to every row of mydata with x being foo, and y being bar?

Yes, I know this specific example is a ridiculously simple and can be done very easily in R, but I'm interested in the pattern.Imagine that myfunction is very complex, and the variable names of myfunction have to be mapped onto the column names of mydata. What is the general solution?

like image 584
user2537291 Avatar asked Dec 12 '22 13:12

user2537291


1 Answers

mydata <- data.frame(x=rnorm(100), y=rnorm(100))
myfunction <- function(x, y) { if (x>0) y else x }

# with plyr (requires the argument names to match)
plyr::mdply(mydata, myfunction)

# with base functions
with(mydata, mapply(myfunction, x, y))
like image 120
baptiste Avatar answered Feb 06 '23 09:02

baptiste