更新时间:2022-02-13 22:53:43
您可以将 apply
应用于原始数据的子集.
You can apply apply
to a subset of the original data.
dat <- data.frame(x=c(1,2), y=c(3,4), z=c(5,6))
apply(dat[,c('x','z')], 1, function(x) sum(x) )
或者如果您的函数只是求和,请使用矢量化版本:
or if your function is just sum use the vectorized version:
rowSums(dat[,c('x','z')])
[1] 6 8
如果你想使用 testFunc
testFunc <- function(a, b) a + b
apply(dat[,c('x','z')], 1, function(x) testFunc(x[1],x[2]))
EDIT 要按名称而不是索引访问列,您可以执行以下操作:
EDIT To access columns by name and not index you can do something like this:
testFunc <- function(a, b) a + b
apply(dat[,c('x','z')], 1, function(y) testFunc(y['z'],y['x']))