In the data frame(df), I need to insert a new column for each group of Sl defining its maximum Value.
df=data.frame(
Sl= c(1,1,2,2,2,2,3,3,4,4,4,5),
Value= c(0,2,1,3,5,2,5,8,10,3,5,7)
)
#Expected outcome:
df$col3=c(2,2,5,5,5,5,5,10,10,7,7,7)
We can use max
by group
library(dplyr)
df %>%
group_by(ID) %>%
mutate(col3 = max(Value))
Maybe you can try ave
dfout <- within(df, col3 <- ave(Value,Sl,FUN = max))