Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cumulative minimum value by group

I want to calculate cumulative min within a given group.

My current data frame:

Group <- c('A', 'A', 'A','A', 'B', 'B', 'B', 'B') 
Target <- c(1, 0, 5, 0, 3, 5, 1, 3) 
data <- data.frame(Group, Target))

My desired output:

Desired.Variable <- c(1, 0, 0, 0, 3, 3, 1, 1)
data <- data.frame(Group, Target, Desired.Variable))

Any help on this would be greatly appreciated!

like image 824
Lisa Avatar asked Oct 17 '22 07:10

Lisa


1 Answers

We could use cummin function by group

data$output <- with(data, ave(Target, Group, FUN = cummin))

data
#  Group Target output
#1     A      1      1
#2     A      0      0
#3     A      5      0
#4     A      0      0
#5     B      3      3
#6     B      5      3
#7     B      1      1
#8     B      3      1

whose dplyr and data.table equivalents are

library(dplyr)
data %>%
  group_by(Group) %>%
  mutate(output = cummin(Target))

library(data.table)
setDT(data)[, output := cummin(Target), by = (Group)]
like image 200
Ronak Shah Avatar answered Oct 30 '22 14:10

Ronak Shah