add_row and do some calculations

Viewed 615

Say I have a data.frame that looks like the below:

df <- data.frame(group = c("group1","group1", "group2", "group2"), 
                 year = c(2000, 2001, 2000, 2001), 
                 value = c(10, 13, 2, 5))

And I want to group by each group, then add a row, then do a calculation on column 3. So for example, the new data frame would look like this (the calculation was simply value(-1)+value(-2))

df <- data.frame(group = c("group1","group1", "group1", "group2", "group2", "group2"), 
                 year = c(2000, 2001, 2002, 2000, 2001, 2002), 
                 value = c(10, 13, 23, 2, 5, 7))

I've tried using dplyr, but I cant seem to figure it out. So I am open to any solution, although if there is a dplyr one that would be great!

Further, I want to be able to do this ten periods into the future so year would be the sequence from 2000 to 2011 in the final data.frame.

1 Answers
Related