title: Calculating age using mutate with lubridate functions
body: <p>I would like to calculate age based on birth date.</p>
  
  <p>If I use lubridate, I would just run the following as in <a href="https://stackoverflow.com/questions/31126726/efficient-and-accurate-age-calculation-in-years-months-or-weeks-in-r-given-b">Efficient and accurate age calculation (in years, months, or weeks) in R given birth date and an arbitrary date</a></p>
  
  <p><code>as.period(new_interval(start = birthdate, end = givendate))$year</code></p>
  
  <p>However, when I tried to use <code>mutate</code> in <code>dplyr</code> to create the new variable,  I ran into an error.</p>
  
  <pre><code>library(dplyr); library(lubridate)
  
  birthdate &lt;- ymd(c(NA, "1978-12-31", "1979-01-01", "1962-12-30"))
  givendate &lt;- ymd(c(NA, "2015-12-31", "2015-12-31", NA))
  
  df &lt;- data.frame(
      birthdate = birthdate,
      givendate = givendate)
  </code></pre>
  
  <p>The following works though it gives all the date and time values. i.e. year, month, day, hour, minute and second.</p>
  
  <pre><code>df&lt;-df %&gt;% mutate(age=as.period(interval(start = birthdate, end = givendate)))
  
  # df
  #    birthdate  givendate                  age
  # 1       &lt;NA&gt;       &lt;NA&gt;                 &lt;NA&gt;
  # 2 1978-12-31 2015-12-31   37y 0m 0d 0H 0M 0S
  # 3 1979-01-01 2015-12-31 36y 11m 30d 0H 0M 0S
  # 4 1962-12-30       &lt;NA&gt;                 &lt;NA&gt;
  </code></pre>
  
  <p>The following does not work:</p>
  
  <pre><code>df&lt;-df %&gt;% 
         mutate(age=as.period(interval(start = birthdate, end = givendate))$year)
  </code></pre>
  
  <p>It gives an error:</p>
  
  <blockquote>
    <p>Error in mutate_impl(.data, dots) : invalid subscript type 'closure'</p>
  </blockquote>
  
  <p>I thought it might be because of the missing values. So, I tried:</p>
  
  <pre><code>df&lt;-df %&gt;% 
     mutate(age=as.period(interval(start = birthdate, end = givendate))) %&gt;% 
     mutate(age=if_else(!is.na(age),age$year,age))
  </code></pre>
  
  <p>It also gives an error:</p>
  
  <blockquote>
    <p>Error in mutate_impl(.data, dots) : object 'age' not found</p>
  </blockquote>