如何将自定义多变量函数应用于R中数据帧的每一行?

use*_*291 4 r function dataframe

假设我有一个数据框,其中的列名为"foo"和"bar"

mydata <- data.frame(foo=rnorm(100), bar=rnorm(100))
Run Code Online (Sandbox Code Playgroud)

并假设我有一个自定义标量函数,它期望标量输入"x"和"y"并产生标量输出,例如

myfunction <- function(x, y) { if (x>0) y else x }
Run Code Online (Sandbox Code Playgroud)

如何将myfunction应用于mydata的每一行,x为foo,y为bar?

是的,我知道这个具体的例子非常简单,可以在R中很容易地完成,但是我对模式感兴趣.想象一下myfunction非常复杂,myfunction的变量名必须映射到列名mydata.什么是一般解决方案?

bap*_*ste 6

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))
Run Code Online (Sandbox Code Playgroud)


dic*_*koa 6

您可以使用 mapply

mapply(myfunction, mydata$foo, mydata$bar)
Run Code Online (Sandbox Code Playgroud)