How to create id variable by grouping sequenced numbers?

后端 未结 4 1300
盖世英雄少女心
盖世英雄少女心 2021-01-28 18:01

I want to add ID variable in this data. If receipt_ids are sequenced numbers, then those have same IDs.

CUST_NO_ID  receipt_id      dollar
  12         29               


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-28 18:38

    Had a similar notion to @Psidom, but he beat me to the punch with cumsum. Here's a dplyr solution. Adding in group_by can give you added flexibility if you want to restart ids by customer number.

    df %>% 
      mutate(id = cumsum(c(TRUE, diff(receipt_id) != 1)))
    

提交回复
热议问题