Apply a function to next row based on previous one for distinct id’s in R

We could group by ‘id’, create the ‘changing_job_position’ based on any duplicated or n_distinct(job_position) >1 along with the row_number and then ungroup and take the lead of the ‘changing_job_position’

library(dplyr)
df %>%
    group_by(id) %>% 
    mutate(changing_job_position = + (any(duplicated(job_position)) &
          row_number() == 1)) %>% 
    ungroup %>% 
    mutate(changing_job_position = lead(changing_job_position, default = 0))

-output

# A tibble: 8 x 3
#     id job_position      changing_job_position
#  <dbl> <chr>                             <dbl>
#1     2 Analyst                               0
#2     2 Supervisor                            1
#3     3 HRBP                                  0
#4     3 HRBP                                  0
#5     4 Economist                             0
#6     4 Financial Planner                     1
#7     5 Reporter                              0
#8     5 Reporter                              0

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top