frazman
frazman

Reputation: 33293

how to do a cumulative count in based on a condition?

I have a data frame like:

 val1,val2
  0, 0
  0, 0
  1, 1
  1, 0
  1, 1

What I want to do is do a cumulative count every time val1 and val2 disagrees

 val1,val2, cum_count
  0, 0,  1
  0, 0,  2
  1, 1,  3
  1, 0,  3 <--- the value here doesn't changes as val1 and val2 disagrees
  1, 1,  4

How do I do this in r?

Upvotes: 2

Views: 214

Answers (1)

mnel
mnel

Reputation: 115465

How about

 dd$cum_count <- with(dd, cumsum(val1==val2))

Upvotes: 4

Related Questions