将n个函数的列表应用于数据帧的每一行?

Abe*_*Abe 11 r apply plyr

我有一个功能列表

funs <- list(fn1 = function(x) x^2,
             fn2 = function(x) x^3,               
             fn3 = function(x) sin(x),
             fn4 = function(x) x+1)
#in reality these are all f = splinefun()
Run Code Online (Sandbox Code Playgroud)

我有一个数据帧:

mydata <- data.frame(x1 = c(1, 2, 3, 2),
                     x2 = c(3, 2, 1, 0),
                     x3 = c(1, 2, 2, 3),
                     x4 = c(1, 2, 1, 2))
#actually a 500x15 dataframe of 500 samples from 15 parameters
Run Code Online (Sandbox Code Playgroud)

对于i行中的每一行,我想评估每个j列上的函数j并对结果求和:

unlist(funs)
attach(mydata)
a <- rep(NA,4)
for (i in 1:4) {
     a[i] <- sum(fn1(x1[i]), fn2(x2[i]), fn3(x3[i]), fn4(x4[i]))
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能有效地做到这一点?这是实施plyr功能的适当场合吗?如果是这样,怎么样?

奖金问题:为什么a[4] NA

这是使用函数的合适时间plyr吗?如果是,我该怎么办?

Pra*_*ani 9

忽略你的代码片段并坚持你想要在列号j上应用函数j的初始规范然后"求和结果"......你可以这样做:

mapply( do.call, funs, lapply( mydata, list))
#      [,1] [,2]      [,3] [,4]
# [1,]    1   27 0.8414710    2
# [2,]    4    8 0.9092974    3
# [3,]    9    1 0.9092974    3
Run Code Online (Sandbox Code Playgroud)

我不确定你现在想要添加结果的方式(即行方式或列方式),所以你可以做rowSums或者colSums在这个矩阵上.例如:

colSums( mapply( do.call, funs,  lapply( mydata, list)) )
# [1] 14.000000 36.000000  2.660066  8.000000
Run Code Online (Sandbox Code Playgroud)