0

I'm trying to make a running maximum column by group in a dataframe. I can do this with a loop through the following but I was wondering if there was a dplyr way of doing this:

df <- data.frame(class=rep(LETTERS,each=20),
                          value=100*rpois(20*26,10))

df$runningMax <- df$value

for (i in 2:nrow(df)) {
  if (df$class[i]==df$class[i-1]) {
    # Running max of class
    df$runningMax[i] = max(df$runningMax[i],df$runningMax[i-1])
  }
}

This was my dplyr attempt:

x <- df %>%
  group_by(class) %>%
      mutate(running_max = value) %>%
      mutate(running_max = max(running_max, lag(running_max)))

Thanks for the help!

zx8754
  • 46,390
  • 10
  • 104
  • 180
tonyk
  • 338
  • 4
  • 21

0 Answers0