如何在R中的数据帧的每一行应用自定义多变量函数? [英] How do I apply a custom multi-variate function to each row of a data frame in R?
问题描述
mydata< - data.frame (foo = rnorm(100),bar = rnorm(100))
标量函数,期望标量输入x和y,并产生标量输出,例如
myfunction< - function (x,y){if(x> 0)y else x}
对于每一行mydata,x是foo,y是bar?
是的,我知道这个具体的例子是一个荒谬的简单,可以很容易地在R中完成,但我对该模式感兴趣。想象一下,我的函数非常复杂,我的函数的变量名必须映射到mydata的列名。什么是一般解决方案?
您可以使用 mapply
p>
mapply(myfunction,mydata $ foo,mydata $ bar)
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?
You can use mapply
mapply(myfunction, mydata$foo, mydata$bar)
这篇关于如何在R中的数据帧的每一行应用自定义多变量函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!