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!
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With