3

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?

Etibar - a tea bar
  • 1,912
  • 3
  • 17
  • 30

1 Answers1

6

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)
Richard Telford
  • 9,558
  • 6
  • 38
  • 51
  • 1
    as suggested by @akrun `df$yes <- cumsum(as.logical(df$State))` and `df$no <- cumsum(!as.logical(df$State))` should work better.. :) – G. Cocca Apr 09 '16 at 17:38
  • @G.Cocca The `as.logical` based on the `'State'` column may not work as the values are `"True"` and `"False"` – akrun Apr 09 '16 at 17:40
  • I assumed that `as.logical` coerces its argument (in this case factor or character) to be of logical type, resulting in a vector of class logical.. What is/are the case where it might not work? – G. Cocca Apr 09 '16 at 20:55
  • as.logical("True") works fine despite the capital case. – Richard Telford Apr 09 '16 at 21:50