How to create id variable by grouping sequenced numbers?

后端 未结 4 1337
盖世英雄少女心
盖世英雄少女心 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:47

    This does it

    id <- 1
    
    for(row in 1:nrow(data)){
      if(row == 1){
        dif <- 1
      }else{
        dif <- data[row,'receipt_id'] - data[row-1,'receipt_id']
      }
    
      if(dif != 1){
        id = id + 1
      }
    
      data[row,'ID'] = id
    }
    

提交回复
热议问题