I changed the indexing from c(.N+1, 1:.N) to c(1L, 1:.N) (from @David Arenburg's post), as this is simpler :-)
library(data.table) setDT(df)[, .SD[c(1L,1:.N)], by=ID][, 2:3 := .SD*(!duplicated(.SD, fromLast=TRUE))+0L, .SDcols=2:3][] # ID TIME DV DOSE pH #1: 1 0 0 50 4.6 #2: 1 1 5 50 4.6 #3: 1 5 10 50 4.6 #4: 2 0 0 100 6.0 #5: 2 1 6 100 6.0 #6: 2 7 10 100 6.0
Or you can use set , which is updated by reference (if there are many columns)
DT <- setDT(df)[, .SD[c(1L, 1:.N)], by=ID] indx <- DT[, !duplicated(.SD, fromLast=TRUE), .SDcols=2:3] for(j in 2:3){ set(DT, i=NULL, j=j, value= DT[[j]]*(indx+0L)) }
akrun source share