Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding index of cummax inside a dplyr mutate?

Tags:

r

dplyr

I have the 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 to add another mutated column which would add the rownumber/index from which the max_then was calculated. I imagine it will be something like the following. but I can't really get it 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 just curious as to see if one can do this within the mutate() statement. I can do it outside of the mutate() statement.

like image 880
Jimbo Avatar asked Jul 20 '15 20:07

Jimbo


1 Answers

I would just 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
like image 95
David Arenburg Avatar answered Nov 15 '22 18:11

David Arenburg