I have this dataframe:
df <- data.frame(group=c("A", "A", "B", "B"), year=c(1980, 1986, 1990, 1992))
group year
1 A 1980
2 A 1986
3 B 1990
4 B 1992
I'd like to modify it in the following way:
- add rows for each existing row with the two preceding years
- add a new column with a variable of the respective year
- delete the existing rows
This would be the outcome:
group year pre
1 A 1978 pre1980
2 A 1979 pre1980
3 A 1984 pre1986
4 A 1985 pre1986
5 B 1988 pre1990
6 B 1989 pre1990
7 B 1990 pre1992
8 B 1991 pre1992
Adding the new column would be easy..
df$pre <- paste("pre", df$year, sep="")
But I am stuck on how to add the new rows with the respective years (of course creating a whole new data frame would be just as good). Any hints?
do.call('rbind', lapply(1:nrow(df), function(x) {x <- df[x, ]; data.frame(group = x$group, year = x$year - 2:1, pre = paste0('pre', x$year))}))