Imagine we have a data set called df, and that this data set is composed of two variables called year and x1:
year <- c(2000, 2001, 2002, 2003, 2004)
x1 <- c(7, 8, 6, 3, 3)
df <- data.frame(year, x1)
My task is to compute two new variables out of x1. The first variable is cSum, which must reflect the sum of the values of x1 for the last two years. The second variable is cMax, which must reflect the highest values for x1 in the last three years.
The outcome should be as follows:
year x1 cSum cMax
2000 7
2001 8 15
2002 6 14 8
2003 3 9 8
2004 3 6 6
How can I compute the cSum and cMax variables above?
Thanks!