How to compute a lag on a variable?


# Consider the following data frame:
data <- data.frame(V1=as.factor(c('yes','no','no','yes','yes','yes','yes')),
(data <- data.frame(ID,data))

# Write code that adds a variable to the data frame data that lags V4
# with 1 value. Important: the first value of each ID should be NA. first value of 1 and 5 row should read NA

In the above exercise you ask us to lag a variable. I understand that it means that each value in the V4 column should be shifted down one
value. What function would allow us to accomplish that and what is the application of a lag in the real world?

Thank you

Answers and follow-up questions

Answer or follow-up question 1

The way you want to approach this is by using a loop.
You would check for each row if the ID in the current row is equal to the previous row.
If that is the case you would take the previous row of V4 and store it in a new variable.

Sign in to be able to add an answer or mark this question as resolved.