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
Filter for the last row per group and set lastconv
equal to conversion
.
DT[DT[, .I[.N], by=id]$V1, lastconv := conversion]
Then replace NA
s 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 NA
s in the second step
DT[DT[, .I[.N], by=id]$V1, lastconv := conversion]
setnafill(DT, cols = "lastconv", fill = 0L)