使用应用:维数不正确

Using apply: Incorrect number of dimensions

data <- data.frame(A = c(1:4), B = c(10:13), C = c(19:22))

我想按行计算 1/A + 1/C

df$calc <- apply(data, 2, function(x) sum(1/x[,c(1,3)])

Error in x[, c(1, 3)] : incorrect number of dimensions

我不明白为什么

fun<- function(x){

 f <- sum(1/x[,c(1,3)])
 return(f)
}

fun(data[1,])
1.052632

工作没有问题

我们可以rowSums,因为它是矢量化的

data$calc <- rowSums(1/data[c("A", "C")])

或者另一个有效的选择是

Reduce(`+`, 1/data[c("A", "C")])

我相信

df <- apply(data, 1, function(x) sum(1/x[c(1,3)])) 是你想要的