Suppose I have the following df,
df <- data.frame(
month = 12:1,
value = c(2,3,4,2,3,4,2,3,4,2,3,4)
)
which contains value for each of the past 12 months. Now I want to add two new columns to record values for past 2 months, for month 12-3, like this:
df2 <- data.frame(
month = 12:3,
value_0 = c(2,3,4,2,3,4,2,3,4,2),
value_1 = c(3,4,2,3,4,2,3,4,2,3),
value_2 = c(4,2,3,4,2,3,4,2,3,4))
This algorithm, when the df gets larger and I want to add n new columns for the past n values, can't be done simply by manually typing... So I wonder, is there a shortcut way to do this? Thank you!