How to create id variable by grouping sequenced numbers?

后端 未结 4 1341
盖世英雄少女心
盖世英雄少女心 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条回答
  •  Happy的楠姐
    2021-01-28 18:42

    We can use data.table

    library(data.table)
    setDT(df)[, id := cumsum(c(TRUE, diff(receipt_id)!=1))]
    

    Or use the shift

    setDT(df)[, id := cumsum((receipt_id - shift(receipt_id, fill=receipt_id[1]))!=1)]
    

提交回复
热议问题