R: creating new variable with conditions using dplyr

Viewed 466

Hi I am trying to create a new variable with dplyr. My data looks like the following:

                Land     happy      year
               <fctr>    <int>     <dbl>
           1  Country1    09       2002
           2  Country1    08       2012
           3  Country3    05       2008
           ...

To create a variable with the mean of happy per Land and year, I used this code:

New <-df %>%
      group_by(Land, year) %>%
      mutate(mean.happy = mean(happy, na.rm=T))

Now I would like to make a variable with this content: (mean of happy in 2012)- (mean of happy in 2008) for each Country.

How can I build a new variable with these conditions?

2 Answers
Related