[英]Incorporating external function in R's apply
Given this data.frame 鉴于此data.frame
x y z
1 1 3 5
2 2 4 6
I'd like to add the value of columns x and z plus a coefficient 10, for every rows in dat
. 我想为
dat
每一行添加列x和z的值加上系数10。 The intended result is this 预期的结果是这样的
x y z result
1 1 3 5 16 #(1+5+10)
2 2 4 6 18 #(2+6+10)
But why this code doesn't produce the desired result? 但为什么这段代码不会产生预期的结果呢?
dat <- data.frame(x=c(1,2), y=c(3,4), z=c(5,6))
Coeff <- 10
# Function
process.xz <- function(v1,v2,cf) {
return(v1+v2+cf)
}
# It breaks here
sm <- apply(dat[,c('x','z')], 1, process.xz(dat$x,dat$y,Coeff ))
# Later I'd do this:
# cbind(dat,sm);
I wouldn't use an apply
here. 我不会在这里
apply
。 Since the addition +
operator is vectorized, you can get the sum using 由于加
+
运算符是矢量化的,因此可以使用求和
> process.xz(dat$x, dat$z, Coeff)
[1] 16 18
To write this in your data.frame
, don't use cbind
, just assign it directly: 要在
data.frame
写这个,不要使用cbind
,只需直接分配:
dat$result <- process.xz(dat$x, dat$z, Coeff)
The reason it fails is because apply doesn't work like that - you must pass the name of a function and any additional parameters. 它失败的原因是因为apply不起作用 - 你必须传递一个函数的名称和任何其他参数。 The rows of the data frame are then passed (as a single vector) as the first argument to the function named.
然后将数据帧的行作为单个向量传递,作为名为的函数的第一个参数。
dat <- data.frame(x=c(1,2), y=c(3,4), z=c(5,6))
Coeff <- 10
# Function
process.xz <- function(x,cf) {
return(x[1]+x[2]+cf)
}
sm <- apply(dat[,c('x','z')], 1, process.xz,cf=Coeff)
I completely agree that there's no point in using apply here though - but it's good to understand anyway. 我完全同意在这里使用申请没有意义 - 但无论如何都要理解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.