How to create a lag variable within each group?

前端 未结 5 1612
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 04:45

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         


        
5条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 05:21

    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.

提交回复
热议问题