1

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)
b_takhel
  • 55
  • 7

2 Answers2

3

We can use max by group

library(dplyr)
df %>% 
   group_by(ID) %>%
    mutate(col3 = max(Value))
akrun
  • 874,273
  • 37
  • 540
  • 662
0

Maybe you can try ave

dfout <- within(df, col3 <- ave(Value,Sl,FUN = max))
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81