到某一行(行)的数据帧的累计和
Cumulative sum of dataframe up to a certain line (row)
我想要以下数据的累计总和:
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, 0), c2 = c(6, 3, 2, 5, 0,
0), c3 = c(3, 2, 5, 4, 0, 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
提前谢谢你。艾伦
这个有用吗:
> 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
csD*(D!=0)
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
) 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
或者如果我们想指定一个行号
D %>%
mutate(across(everything(), ~ case_when(row_number() <=4 ~
cumsum(.), TRUE ~ .)))
我想要以下数据的累计总和:
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, 0), c2 = c(6, 3, 2, 5, 0,
0), c3 = c(3, 2, 5, 4, 0, 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
提前谢谢你。艾伦
这个有用吗:
> 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
csD*(D!=0)
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
) 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
或者如果我们想指定一个行号
D %>%
mutate(across(everything(), ~ case_when(row_number() <=4 ~
cumsum(.), TRUE ~ .)))