gpt4 book ai didi

对某些列进行逐行累加和,然后进行逐行除法

转载 作者:行者123 更新时间:2023-12-02 15:48:42 26 4
gpt4 key购买 nike

我有以下数据框:

New_Sign_ups   Spend   2021-05  2021-06      2021-07  MRR_sum  time
100 100 0 10 100 110 1.5
50 200 10 10 40 60 1.8

首先,我需要对第 3 ~ 5 列进行逐行累计和:

New_Sign_ups   Spend   2021-05  2021-06      2021-07  MRR_sum  time
100 100 0 10 110 110 1.5
50 200 10 20 60 60 1.8

然后我需要将累积总和除以该行的 Spend 值:

New_Sign_ups   Spend   2021-05  2021-06      2021-07  MRR_sum  time
100 100 0 0.1 1.1 110 1.5
50 200 0.05 0.1 0.3 60 1.8

我该怎么做?

最佳答案

dat <- structure(list(New_Sign_ups = c(100L, 50L), Spend = c(100L, 200L
), `2021-05` = c(0L, 10L), `2021-06` = c(10L, 10L), `2021-07` = c(100L,
40L), MRR_sum = c(110L, 60L), time = c(1.5, 1.8)), class = "data.frame",
row.names = c(NA, -2L))

不使用任何包

dat[3:5] <- do.call("cbind", Reduce(`+`, dat[3:5], accumulate = TRUE)) / dat$Spend
# New_Sign_ups Spend 2021-05 2021-06 2021-07 MRR_sum time
#1 100 100 0.00 0.1 1.1 110 1.5
#2 50 200 0.05 0.1 0.3 60 1.8

使用包 matrixStats

library(matrixStats)
dat[3:5] <- rowCumsums(as.matrix(dat[3:5])) / dat$Spend
# New_Sign_ups Spend 2021-05 2021-06 2021-07 MRR_sum time
#1 100 100 0.00 0.1 1.1 110 1.5
#2 50 200 0.05 0.1 0.3 60 1.8

关于对某些列进行逐行累加和,然后进行逐行除法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73284325/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com