Sum of previous rows in a column R

柔情痞子 提交于 2019-12-18 09:08:08

问题


I have table as following

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

I need to count true and false until showed row . So the result should be as the following 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

Until 6th(including 6th) row there are 3 False and 3 True. Any ideas?


回答1:


Does this do what you want?

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

Or if you have df$State as a logical vector

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


来源:https://stackoverflow.com/questions/36517621/sum-of-previous-rows-in-a-column-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!