R 列中前几行的总和

Sum of previous rows in a column R

我有table如下

id State
1 True
2 False
3 True
4 False
5 False
6 True
7 True
8 False

我需要计算 true 和 false 直到显示行。所以结果应该如下table

id State  Yes   No
1 True      1   0
2 False     1   1
3 True      2   1
4 False     2   2
5 False     2   3
6 True      3   3
7 True      4   3
8 False     4   4

直到第6(包括第6)行有3个错误和3个正确。有什么想法吗?

这是你想要的吗?

df$yes <- cumsum(df$State == "True")
df$no <- cumsum(df$State == "False")

或者如果您将 df$State 作为逻辑向量

df$yes <- cumsum(df$State)
df$no <- cumsum(!df$State)