我有一个以下格式的数据框
> x <- data.frame("a" = c(1,1),"b" = c(2,2),"c" = c(3,4))
> x
a b c
1 1 2 3
2 1 2 4
我想添加3个新列,这是a b c列的累积乘积,但是我需要一个反向累积积,即输出应为
row 1:
result_d = 1*2*3 = 6 , result_e = 2*3 = 6, result_f = 3
以及类似的第二行
最终结果将是
a b c result_d result_e result_f
1 1 2 3 6 6 3
2 1 2 4 8 8 4
列名无关紧要,这只是一个示例。有谁知道如何做到这一点?
根据我的评论,是否可以在一部分列上执行此操作?例如仅让b和c列返回:
a b c results_e results_f
1 1 2 3 6 3
2 1 2 4 8 4
以便有效地忽略“ a”列?
答案 0 :(得分:2)
一种选择是遍历各行并将cumprod
应用于元素的rev
,然后进行rev
erse
nm1 <- paste0("result_", c("d", "e", "f"))
x[nm1] <- t(apply(x, 1,
function(x) rev(cumprod(rev(x)))))
x
# a b c result_d result_e result_f
#1 1 2 3 6 6 3
#2 1 2 4 8 8 4
或向量化选项为rowCumprods
library(matrixStats)
x[nm1] <- rowCumprods(as.matrix(x[ncol(x):1]))[,ncol(x):1]
答案 1 :(得分:0)
temp = data.frame(Reduce("*", x[NCOL(x):1], accumulate = TRUE))
setNames(cbind(x, temp[NCOL(temp):1]),
c(names(x), c("res_d", "res_e", "res_f")))
# a b c res_d res_e res_f
#1 1 2 3 6 6 3
#2 1 2 4 8 8 4