直到某行行的数据帧的累积总和

问题描述

我想累积以下数据的总和:

    c1    c2    c3
    
1     3     6     3
2     4     3     2
3     6     2     5
4     1     5     4
5     0     0     0
6     0     0     0

,但最多4行(行)。例如,下面的代码将产生数据帧的一般累积总和,包括列中的所有行

library(readxl)
library(xts)
library("xlsx")
library(dplyr)
library(data.table)
library(tidyverse)

D <- structure(list(c1 = c(3,4,6,1,0),c2 = c(6,3,2,5,c3 = c(3,0)),row.names = c(NA,-6L),class = c("tbl_df","tbl","data.frame"))
D
csD <- cumsum(D)
csD

产生

     c1    c2    c3
    
1     3     6     3
2     7     9     5
3    13    11    10
4    14    16    14
5    14    16    14
6    14    16    14

但是,我希望拥有:

     c1    c2    c3
    
1     3     6     3
2     7     9     5
3    13    11    10
4    14    16    14
5     0     0     0
6     0     0     0

先谢谢您。艾伦

解决方法

true
,

这项工作:

> rbind(cumsum(D[1:(min(which(rowSums(D) == 0))-1),]),cumsum(D[min(which(rowSums(D) == 0)):nrow(D),]))
# A tibble: 6 x 3
     c1    c2    c3
  <dbl> <dbl> <dbl>
1     3     6     3
2     7     9     5
3    13    11    10
4    14    16    14
5     0     0     0
6     0     0     0
> 
,

也许不是最佳方法,但您可以定义N并使用apply()rbind(),如下所示:

#Code
#Define N
N <- 4
#Compute
newdf <- rbind(apply(D,2,function(x) cumsum(x[1:N])),D[(N+1):nrow(D),])

输出:

newdf
  c1 c2 c3
1  3  6  3
2  7  9  5
3 13 11 10
4 14 16 14
5  0  0  0
6  0  0  0
,

我们可以将NA转换为0(na_if),获取cumsum并将NA替换为0(replace_na){{1} }所有列

across

-输出

library(dplyr)
library(tidyr)
D %>% 
       mutate(across(everything(),~replace_na(cumsum(na_if(.,0)),0)))

或者我们要指定行号

# A tibble: 6 x 3
#     c1    c2    c3
#  <dbl> <dbl> <dbl>
#1     3     6     3
#2     7     9     5
#3    13    11    10
#4    14    16    14
#5     0     0     0
#6     0     0     0