title: dplyr mutate(): ignore values if group is NA
body: <p>I'm a newcommer to <code>dplyr</code> and have following question. My has <code>data.frame</code> one column serving as a grouping variable. Some rows <em>don't</em> belong to a group, the grouping column being <code>NA</code>. </p>
  
  <p>I need to add some columns to the data.frame using the <code>dplyr</code> function <code>mutate</code>. I'd prefer that <code>dplyr</code> ignores all rows where the grouping column equals to <code>NA</code>.  I'll illustrate with an example:</p>
  
  <pre><code>library(dplyr)
  
  set.seed(2)
  
  # Setting up some dummy data
  df &lt;- data.frame(
    Group = factor(c(rep("A",3),rep(NA,3),rep("B",5),rep(NA,2))),
    Value = abs(as.integer(rnorm(13)*10))
  )
  
  # Using mutate to calculate differences between values within the rows of a group
  df &lt;- df %&gt;%
    group_by(Group) %&gt;%
    mutate(Diff = Value-lead(Value))
  
  df
  # Source: local data frame [13 x 3]
  # Groups: Group [3]
  # 
  #     Group Value  Diff
  #    (fctr) (int) (int)
  # 1       A     8     7
  # 2       A     1   -14
  # 3       A    15    NA
  # 4      NA    11    11
  # 5      NA     0    -1
  # 6      NA     1    -8
  # 7       B     7     5
  # 8       B     2   -17
  # 9       B    19    18
  # 10      B     1    -3
  # 11      B     4    NA
  # 12     NA     9     6
  # 13     NA     3    NA
  </code></pre>
  
  <p>Calculating the differences between rows without a group makes no sense and is corrupting the data. I need to remove these rows and have done so like this:</p>
  
  <pre><code>df$Diff[is.na(df$Group)]  &lt;- NA
  </code></pre>
  
  <p>Is there a way to include the above command into the dplyr-chain using %>% ? Somewhere in the lines of:</p>
  
  <pre><code>df &lt;- df %&gt;%
    group_by(Group) %&gt;%
    mutate(Diff = Value-lead(Value)) %&gt;%
    filter(!is.na(Group))
  </code></pre>
  
  <p>But where the rows without a group are not removed all together? Or even better, is there a way to make <code>dplyr</code> ignore rows without a group?</p>
  
  <p>There desired outcome would be:</p>
  
  <pre><code># Source: local data frame [13 x 3]
  # Groups: Group [3]
  # 
  #     Group Value  Diff
  #    (fctr) (int) (int)
  # 1       A     8     7
  # 2       A     1   -14
  # 3       A    15    NA
  # 4      NA    11    NA
  # 5      NA     0    NA
  # 6      NA     1    NA
  # 7       B     7     5
  # 8       B     2   -17
  # 9       B    19    18
  # 10      B     1    -3
  # 11      B     4    NA
  # 12     NA     9    NA
  # 13     NA     3    NA
  </code></pre>