title: Rearrange Dates r
body: <p>I have three columns of dates.</p>
  
  <pre><code>test &lt;- data.frame(a = as.Date(rep("2008-02-04", 5)),
                 b = as.Date(c("2010-01-25",
                               "2012-04-13",
                               "2013-04-04",
                               "2013-09-06",
                               "2014-08-14")),
                 c = as.Date(c("2010-01-29",
                               "2012-04-16",
                               NA,
                               "2013-09-19",
                               "2014-08-21"))); test
             a          b          c
  1 2008-02-04 2010-01-25 2010-01-29
  2 2008-02-04 2012-04-13 2012-04-16
  3 2008-02-04 2013-04-04       &lt;NA&gt;
  4 2008-02-04 2013-09-06 2013-09-19
  5 2008-02-04 2014-08-14 2014-08-21
  </code></pre>
  
  <p>I would like to rearrange them in the following position. What happens is that I take row A value is replaced by the C value from previous row. And in case previous row C is NA, than value from previous row B is taken and placed into current a.</p>
  
  <pre><code>           a          b          c
  1 2008-02-04 2010-01-25 2010-01-29
  2 2010-01-29 2012-04-13 2012-04-16
  3 2012-04-16 2013-04-04       &lt;NA&gt;
  4 2013-04-04 2013-09-06 2013-09-19
  5 2013-09-19 2014-08-14 2014-08-21
  </code></pre>
  
  <p>So far I've solved this with for loop:</p>
  
  <pre><code>n &lt;- nrow(test)
  if (n &gt; 1) {
    for (i in 1:(n - 1)) {
      empty &lt;- is.na(test$c[i])
      if (empty)
        test$a[i + 1] &lt;- test$b[i]
      else
        test$a[i + 1] &lt;- test$c[i]
    }
  }
  </code></pre>
  
  <p>I want to know if there is any faster way to do this by using dplyr package. I wanted to use mutate with ifelse statement but I do not know how to select i+1 for the variable I want to change. I tryed to do the following:</p>
  
  <pre><code>test %&gt;% mutate(a = if_else(is.na(lag(c, n = 1)),
                              true = lag(b, n = 1),
                              false = lag(c, n = 1),
                              missing = a))
  </code></pre>
  
  <p>But this always returns NA for first item in row a:</p>
  
  <pre><code>           a          b          c
  1       &lt;NA&gt; 2010-01-25 2010-01-29
  2 2010-01-29 2012-04-13 2012-04-16
  3 2012-04-16 2013-04-04       &lt;NA&gt;
  4 2013-04-04 2013-09-06 2013-09-19
  5 2013-09-19 2014-08-14 2014-08-21
  </code></pre>