将n个函数的列表应用于数据帧的每一行? [英] Apply a list of n functions to each row of a dataframe?

查看:66
本文介绍了将n个函数的列表应用于数据帧的每一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有功能列表

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()

我有一个数据框:

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

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

For each of i rows, I would like to evaluate function j on each of the j columns and sum the results:

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]))
}

如何有效地做到这一点?这是实现plyr功能的合适时机吗?如果可以,怎么办?

How can I do this efficiently? Is this an appropriate occasion to implement plyr functions? If so, how?

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

现在是使用plyr中的函数的合适时间吗,如果可以,该如何使用?

Is this an appropriate time to use functions from plyr, if so, how can I do so?

推荐答案

忽略代码段,并坚持要在列号 j <上应用函数 j 的初始规范. /em>,然后对结果求和" ...您可以这样做:

Ignoring your code snippet and sticking to your initial specification that you want to apply function j on the column number j and then "sum the results"... you can do:

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

我不确定现在要以哪种方式添加结果(即按行或按列),因此可以在此矩阵上执行rowSumscolSums.例如:

I wasn't sure which way you want to now add the results (i.e. row-wise or column-wise), so you could either do rowSums or colSums on this matrix. E.g:

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

这篇关于将n个函数的列表应用于数据帧的每一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆