I want to create a lag variable in my dataframe.
I have a list of time c("20110127", "20110128", "20110129", "20110130", "20110131", "20110201", "20110202").
My dataframe look like:
| ID | TIME | VALUE |
|---|---|---|
| 1 | 20110127 | 3.23 |
| 1 | 20110128 | 4.57 |
| 1 | 20110130 | 3.22 |
| 1 | 20110131 | 4.33 |
| 1 | 20110202 | 5.23 |
| 2 | 20110127 | 0.86 |
| 2 | 20110128 | 7.55 |
| 2 | 20110129 | 1.24 |
| 2 | 20110201 | 3.69 |
The year in the table is not consecutive. And I want to group_by ID then create a one-day lag variable. Which look like this:
| ID | TIME | VALUE | LAG |
|---|---|---|---|
| 1 | 20110127 | 3.23 | NA |
| 1 | 20110128 | 4.57 | 3.23 |
| 1 | 20110130 | 3.22 | NA |
| 1 | 20110131 | 4.33 | 3.22 |
| 1 | 20110201 | 1.22 | 4.33 |
| 1 | 20110202 | 5.23 | 1.22 |
| 2 | 20110127 | 0.86 | NA |
| 2 | 20110128 | 7.55 | 0.86 |
| 2 | 20110129 | 1.24 | 7.55 |
| 2 | 20110201 | 3.69 | NA |
I tried
alltime = c("20110127", "20110128", "20110129", "20110130", "20110131", "20110201", "20110202")
last_day = data %>%
arrange(ID, TIME) %>%
group_by(ID) %>%
mutate(lagtime = alltime[which(alltime == TIME)+1], lagoutput = value ,value = NULL)
data %>%
left_join(last_day)
But it seems like the mutate function wouldn't work here. Maybe the problem is alltime[which(alltime == TIME)+1] and I cannot create a lag.
Appreciate any comment.