Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

roc - Sum of previous rows in a column R

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...