I have a data.table:
set.seed(1)
data <- data.table(time = c(1:3, 1:4),
groups = c(rep(c(\"b\", \"a\"), c(3, 4))),
v
In base R, this will do the job:
data$lag.value <- c(NA, data$value[-nrow(data)])
data$lag.value[which(!duplicated(data$groups))] <- NA
The first line adds a string of lagged (+1) observations. The second string corrects the first entry of each group, as the lagged observation is from previous group.
Note that data is of format data.frame to not use data.table.