2015-07-20 60 views
8

我有以下代码:在dplyr突变体内找到cummax的指数?

library(dplyr) 
set.seed(10) 
test<-data.frame(x=runif(10,0,1),y=rep(c(1,2),5)) 
test <- test %>% 
    group_by(y) %>% 
    mutate(max_then=cummax(x)) 

test 

其输出

Source: local data frame [10 x 3] 
Groups: y 

      x y max_then 
1 0.50747820 1 0.5074782 
2 0.30676851 2 0.3067685 
3 0.42690767 1 0.5074782 
4 0.69310208 2 0.6931021 
5 0.08513597 1 0.5074782 
6 0.22543662 2 0.6931021 
7 0.27453052 1 0.5074782 
8 0.27230507 2 0.6931021 
9 0.61582931 1 0.6158293 
10 0.42967153 2 0.6931021 

我要添加另一个突变的列这将增加从该计算出的max_then ROWNUMBER /索引。我想它会像下面这样。但我无法真正实现它的工作。

test %>% 
group_by(y) %>% 
    mutate(max_then-cummax(x), 
      max_index=which(.$x==max_then)) 

预期成果是:

  x y max_then max_index 
1 0.50747820 1 0.5074782   1 
2 0.30676851 2 0.3067685   2 
3 0.42690767 1 0.5074782   1 
4 0.69310208 2 0.6931021   4 
5 0.08513597 1 0.5074782   1 
6 0.22543662 2 0.6931021   4 
7 0.27453052 1 0.5074782   1 
8 0.27230507 2 0.6931021   4 
9 0.61582931 1 0.6158293   9 
10 0.42967153 2 0.6931021   4 

有什么建议?我只是很好奇,看看是否可以在mutate()语句中做到这一点。我可以在mutate()语句之外做到这一点。

+2

请使用'set.seed'。另外,你可以将它减少到10行。最后,请提供您想要的输出。 –

回答

10

我只想匹配唯一实例在X

test %>% 
    mutate(max_index = match(max_then, unique(test$x))) 
# Source: local data frame [10 x 4] 
# Groups: y 
# 
#    x y max_then max_index 
# 1 0.50747820 1 0.5074782   1 
# 2 0.30676851 2 0.3067685   2 
# 3 0.42690767 1 0.5074782   1 
# 4 0.69310208 2 0.6931021   4 
# 5 0.08513597 1 0.5074782   1 
# 6 0.22543662 2 0.6931021   4 
# 7 0.27453052 1 0.5074782   1 
# 8 0.27230507 2 0.6931021   4 
# 9 0.61582931 1 0.6158293   9 
# 10 0.42967153 2 0.6931021   4 
+1

匹配是我正在寻找感谢 – Jimbo

+1

你不应该需要'测试$'? – hadley

+0

@hadley它无法正常工作。看起来你需要将它与'ungroup()'或其他东西结合起来才能使它工作。 –