Assigning values in a sequence depending on previous row in R

前端 未结 1 1889

I have a data table like this.

  ID1 ID2 member
1   a   x parent
2   a   y  child
3   a   z parent
4   a   p  child
5   a   q  child
6   b   x parent
7   b           


        
相关标签:
1条回答
  • 2021-01-05 12:21

    Here's one way with seq:

    dt[ , sequence := seq(.N), by = cumsum(member == "parent")]
    
    #    ID1 ID2 member sequence
    # 1:   a   x parent        1
    # 2:   a   y  child        2
    # 3:   a   z parent        1
    # 4:   a   p  child        2
    # 5:   a   q  child        3
    # 6:   b   x parent        1
    # 7:   b   z parent        1
    # 8:   b   q  child        2
    

    How it works?

    The command member == "parent" creates a logical vector. The function cumsum is used to calculate the cumulative sum. In this case, it creates vector in which a parent and the following childs have the same number. This vector is used for grouping. Finally, seq(.N) creates a sequence from 1 up to the number of elements in the group.

    0 讨论(0)
提交回复
热议问题