i have following code:
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 which outputs
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 i want add mutated column add rownumber/index max_then calculated. imagine following. can't work.
test %>% group_by(y) %>% mutate(max_then-cummax(x), max_index=which(.$x==max_then)) expected output is:
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 any suggestions? i'm curious see if 1 can within mutate() statement. can outside of mutate() statement.
i match unique instances in 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
Comments
Post a Comment