在数据框的每一行上调用类似应用的函数,每一行具有多个参数

我有一个多列的数据框。对于数据框中的每一行,我想在该行上调用一个函数,并且该函数的输入正在使用该行中的多个列。例如,假设我有此数据和接受两个参数的testFunc:


> df <- data.frame(x=c(1,2), y=c(3,4), z=c(5,6))

> df

  x y z

1 1 3 5

2 2 4 6

> testFunc <- function(a, b) a + b

假设我想将此testFunc应用于列x和z。因此,对于第1行,我想要1 + 5,对于第2行,我想要2 + 6。是否有一种无需编写for循环就能做到这一点的方法,也许可以使用apply函数族?


我尝试了这个:


> df[,c('x','z')]

  x z

1 1 5

2 2 6

> lapply(df[,c('x','z')], testFunc)

Error in a + b : 'b' is missing

但是有错误,有什么想法吗?


编辑:我要调用的实际函数不是一个简单的总和,而是power.t.test。我仅出于示例目的使用a + b。最终目标是能够执行以下操作(用伪代码编写):


df = data.frame(

    delta=c(delta_values), 

    power=c(power_values), 

    sig.level=c(sig.level_values)

)


lapply(df, power.t.test(delta_from_each_row_of_df, 

                        power_from_each_row_of_df, 

                        sig.level_from_each_row_of_df

))

其中结果是df每行的power.t.test输出的向量。


潇潇雨雨
浏览 761回答 3
3回答

慕工程0101907

您可以将其应用于apply原始数据的子集。&nbsp;dat <- data.frame(x=c(1,2), y=c(3,4), z=c(5,6))&nbsp;apply(dat[,c('x','z')], 1, function(x) sum(x) )或者如果您的函数只是求和,请使用向量化版本:rowSums(dat[,c('x','z')])[1] 6 8如果要使用 testFunc&nbsp;testFunc <- function(a, b) a + b&nbsp;apply(dat[,c('x','z')], 1, function(x) testFunc(x[1],x[2]))编辑要通过名称访问列而不是索引,您可以执行以下操作:&nbsp;testFunc <- function(a, b) a + b&nbsp;apply(dat[,c('x','z')], 1, function(y) testFunc(y['z'],y['x']))

qq_遁去的一_1

dplyr套餐的新答案如果要应用的功能是矢量化的,则可以使用软件包中的mutate功能dplyr:> library(dplyr)> myf <- function(tens, ones) { 10 * tens + ones }> x <- data.frame(hundreds = 7:9, tens = 1:3, ones = 4:6)> mutate(x, value = myf(tens, ones))&nbsp; hundreds tens ones value1&nbsp; &nbsp; &nbsp; &nbsp; 7&nbsp; &nbsp; 1&nbsp; &nbsp; 4&nbsp; &nbsp; 142&nbsp; &nbsp; &nbsp; &nbsp; 8&nbsp; &nbsp; 2&nbsp; &nbsp; 5&nbsp; &nbsp; 253&nbsp; &nbsp; &nbsp; &nbsp; 9&nbsp; &nbsp; 3&nbsp; &nbsp; 6&nbsp; &nbsp; 36plyr包装的旧答案我认为,最适合该任务的工具mdply来自plyr包装。例:> library(plyr)> x <- data.frame(tens = 1:3, ones = 4:6)> mdply(x, function(tens, ones) { 10 * tens + ones })&nbsp; tens ones V11&nbsp; &nbsp; 1&nbsp; &nbsp; 4 142&nbsp; &nbsp; 2&nbsp; &nbsp; 5 253&nbsp; &nbsp; 3&nbsp; &nbsp; 6 36不幸的是,正如Bertjan Broeksema指出的那样,如果您没有在mdply调用中使用数据帧的所有列,则此方法将失败。例如,> library(plyr)> x <- data.frame(hundreds = 7:9, tens = 1:3, ones = 4:6)> mdply(x, function(tens, ones) { 10 * tens + ones })Error in (function (tens, ones)&nbsp; : unused argument (hundreds = 7)
打开App,查看更多内容
随时随地看视频慕课网APP