I want to calculate cumulative min
within a given group.
My current data frame:
Group <- c(\'A\', \'A\', \'A\',\'A\', \'B\', \'B\', \'B
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)]