鉴于:
test <- data.frame(Participant= c(1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3),
Day = c(0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9),
Value= c(1:30))
我想到达:
test <- data.frame(Participant= c(1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3),
Day = c(0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9),
Value= c(1:30),
LaggedValue= c("NA", 1,2,3,4,5,6,7,8,9, "NA", 11,12,13,14,15,16,17,18,19, "NA", 21,22,23,24,25,26,27,28,29))
我尝试了以下方法,它允许我对变量进行时间滞后,但在整个列中都这样做。我想根据 ParticipantID 或 Day 变量进行时间滞后,以便在遇到新的参与者编号或 Day=0 时,时间滞后返回“NA”:
test$LaggedValue <- c(NA, test$Value[seq_along(test$Value) -1])
我不确定如何添加“if”语句或基于 Participant/Day 变量。nest() 函数可能在这里工作吗?