2012-07-06 19 views
0

我确定这已经被问过,但对于我的生活我无法弄清楚要搜索什么!每一行的剧集数量

,我有以下数据:

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

而且我想输出一个正在运行的计数重置每次X或Y的变化值。

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 
+1

相关 - HTTP:// stackoverflow.com/questions/8997638/numbering-by-groups – Dason 2012-07-06 22:46:19

+0

是的。但是这个增加了两个组的分裂,并不是所有这些解决方案都是相关的 – 2012-07-06 23:03:49

回答

2

试着这么做

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 
+0

BINGO! 我想知道如果粘贴和rle会涉及! – 2012-07-06 23:33:34

0

在看到@ ttmaccer的我看到我的ave第一次尝试是错误的,这或许需要什么:

> 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