I have a data frame with the following simplified structure:
df <- data.frame(Id = c(1,1,1,2,2,2,3,3,3,4,4,4),
value = c(500,500,500,250,250,250,300,300,300,400,400,400))
and I am trying to get the following desired output:
df$maxByGroup <- c(500,0,0,250,0,0,300,0,0,400,0,0)
I have tried this:
df$Id <- as.factor(df$Id)
newDf <- df %>%
group_by(Id) %>%
summarise(maxByGroup = sum(max(value)))
and just get the maximum of 500 returned.
I have looked at other solutions that get the max value easily enough but I cannot find one that gives the max value and returns 0 for the other values within each group.
The most important aspect of the desired output is I want to maintain the data structure but have the first observation within each group to reflect the maximum and the rest to be recoded as zero. Any help that anyone could provide would be very much appreciated.