0

I'm sure this has been asked before but for the life of me I can't figure out what to search for!

I have the following data:

x y  
1 3  
1 3  
1 3  
1 2  
1 2  
2 2  
2 4  
3 4  
3 4

And I would like to output a running count that resets everytime either x or y changes value.

x y o  
1 3 1  
1 3 2  
1 3 3  
1 2 1  
1 2 2  
2 2 1  
2 4 1  
3 4 1  
3 4 2
IRTFM
  • 258,963
  • 21
  • 364
  • 487

2 Answers2

2

Try something like

df<-read.table(header=T,text="x y
1 3
1 3
1 3
1 2
1 2
2 2
2 4
3 4
3 4")

cbind(df,o=sequence(rle(paste(df$x,df$y))$lengths))

> cbind(df,o=sequence(rle(paste(df$x,df$y))$lengths))
  x y o
1 1 3 1
2 1 3 2
3 1 3 3
4 1 2 1
5 1 2 2
6 2 2 1
7 2 4 1
8 3 4 1
9 3 4 2
shhhhimhuntingrabbits
  • 7,397
  • 2
  • 23
  • 23
0

After seeing @ttmaccer's I see my first attempt with ave was wrong and this is perhaps what is needed:

> dat$o <- ave(dat$y, list(dat$y, dat$x), FUN=seq )
# there was a warning but the answer is corect.
> dat
  x y o
1 1 3 1
2 1 3 2
3 1 3 3
4 1 2 1
5 1 2 2
6 2 2 1
7 2 4 1
8 3 4 1
9 3 4 2
IRTFM
  • 258,963
  • 21
  • 364
  • 487