Hi, I need to add a new column in my dataset that will include lag values. See simplified example:
df <- data.frame(Code=c("01","01", "02","02","03"), Date = c("01-01-2005","02-01-2005","01-01-2005","02-01-2005","01-01-2005"),
Value=c(5,10, 6, 7, 8))
My desired output is this:
df1 <- data.frame(Code=c("01","01", "02","02","03"), Date = c("01-01-2005","02-01-2005","01-01-2005","02-01-2005","01-01-2005"),
Value=c(5,10, 6, 7, 8), lag1 = c(NA, 5, NA, 6, NA))
I tried to use dplyr package, but this solution wasn`t successful:
df1 <-
df %>%
group_by(Code) %>%
mutate(lag1 = dplyr::lag(count, n = 1, default = NA))
I got this error message:
Error: Problem with `mutate()` input `lag1`.
x Input must be a vector, not a function.
i Input `lag1` is `dplyr::lag(count, n = 1, default = NA)`.
i The error occurred in group 1: Code = "01".
How can I fix it please? Thanks a lot.