5 Answers
5

New function shift() implements fast lead/lag of vector, list, data.frames or data.tables. It takes a type argument which can be either "lag" (default) or "lead" and always returns a list, which makes it very convenient to use it along with := or set(). For example: DT[, (cols) := shift(.SD, 1L), by=id]. Please have a look at ?shift for more info.

We can therefore now simply do:

DT[ , D := C + shift(B, 1L, type="lag")[[1L]] ]

Old solution:

DT[, D := C + c(NA, B[1:(.N-1)])][] # the last [] is to print the result

Several folks have answered the specific question. See the code below for a general purpose function that I use in situations like this that may be helpful. Rather than just getting the prior row, you can go as many rows in the "past" or "future" as you'd like.

This is a brilliant answer, I'm annoyed that I've already upvoted the other answers because this is a far more general answer. In fact, I'm going to use it in my geneorama package (if you don't mind).
–
geneoramaNov 3 '14 at 19:52

Sure, go for it. I was hoping to get some free time and submit it as a pull request to the data.table package, but alas...
–
dnlbrkyNov 3 '14 at 20:33

A similar function called shift has been added to data.table as of version 1.9.5. See the updated answer from @Arun.
–
dnlbrkyFeb 19 at 18:53