R data.table binary value for last row in group by condition

前端 未结 5 1904
感情败类
感情败类 2021-01-18 00:15

I have data like this:

library(data.table)
id <- c(\"1232\",\"1232\",\"1232\",\"4211\",\"4211\",\"4211\")
conversion <- c(0,0,0,1,1,1)
DT <- data.ta         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-18 01:00

    Filter for the last row per group and set lastconv equal to conversion.

    DT[DT[, .I[.N], by=id]$V1, lastconv := conversion]
    

    Then replace NAs with 0

    DT[is.na(lastconv), lastconv := 0L]
    

    Result

    DT
    #     id conversion lastconv
    #1: 1232          0        0
    #2: 1232          0        0
    #3: 1232          0        0
    #4: 4211          1        0
    #5: 4211          1        0
    #6: 4211          1        1
    

    If data.table v1.12.3 is installed we could also use the new function setnafill to replace NAs in the second step

    DT[DT[, .I[.N], by=id]$V1, lastconv := conversion]
    setnafill(DT, cols = "lastconv", fill = 0L)
    

提交回复
热议问题