Chega
Chega

Reputation: 195

How to count changes in a column

I am searching for a simple way to count changes occurring in a column "AA" of my data frame; so the new column "BB" should look like in the df given below:

df <- as.data.frame(cbind("Year"=c(2000,2000,2000,2001,2001,2001,2002,2002,2002,2003), "AA"=c(136,137,137,158,162,21,21,55,55,55), "BB"=c(1,2,2,3,4,5,5,6,6,6)))

In other words, any change (increase or decrease) in "AA" should be accounted for in "BB" by adding up...

Upvotes: 2

Views: 760

Answers (2)

Roland
Roland

Reputation: 132706

I prefer using cumsum like this:

df$BB <-  cumsum(c(1, head(df$AA, -1) != tail(df$AA, -1)))

Benchmarks with x <- sample(1:10,1e4,TRUE):

Unit: microseconds
   expr  min   lq median   uq  max neval
 Jus(x) 1259 1330   1936 1987 5289   100
 Rol(x)  391  402    463  616 3903   100

Upvotes: 6

Justin
Justin

Reputation: 43255

I like rle for this:

foo <- rle(df$AA)
foo$values <- 1:length(foo$values)
df$BB <- inverse.rle(foo)

Upvotes: 6

Related Questions