how do i apply a function within a group that depends on which row within the group holds a value?

You can use which or better which.max which is guaranteed to return only 1 value.

library(dplyr)

df %>%
  group_by(ID) %>%
  mutate(which = which.max(value) * +(row_number() == 1))

#     ID level value which
#  <int> <int> <int> <int>
#1     1     1     0     3
#2     1     2     0     0
#3     1     3     1     0
#4     2     1     0     2
#5     2     2     1     0
#6     2     3     0     0

+(row_number() == 1) is to ensure that the value of which is assigned to only 1st row in the group and rest all the rows are 0.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top