Collapse columns into one, removing NA, function if both not NA
<p>I have some data regarding separation in <code>x</code> and <code>y</code> as a function of time.
There can be a separation only in <code>x</code>, only in <code>y</code>, or both (diagonal, with <code>x==y</code>):</p>

<pre><code>data
#  Source: local data frame [307 x 4]

#             t0         t1             x             y
# 1   1449241093 1449241345            NA  4.085057e-02
# 2   1449241345 1449241537            NA  4.085057e-02
# ...
# 7   1449242375 1449242627  4.085057e-02            NA
# 8   1449242627 1449242818  4.085057e-02            NA
# ...
# 78  1449245524 1449246079  0.000000e+00  0.000000e+00
# 79  1449246079 1449246101 -2.042528e-01 -2.042528e-01
# ...
</code></pre>

<p>I want to bring this into this format:</p>

<pre><code># Source: local data frame [307 x 4]

#            t0         t1 direction    separation
# 1  1449241093 1449241345         Y  4.085057e-02
# 2  1449241345 1449241537         Y  4.085057e-02
# ...
# 8  1449242627 1449242818         X  4.085057e-02
# 9  1449242818 1449242949         X  4.085057e-02
# ...
# 78  1449245524 1449246079        D  0.000000e+00
# 79  1449246079 1449246101        D  2.888571e-01
# ...
</code></pre>

<p>Currently I'm doing this using code like this:</p>

<pre><code>data %&gt;% mutate(direction=ifelse(is.na(x),"Y", ifelse(is.na(y),"X","D")),
                separation=ifelse(is.na(x),y, ifelse(is.na(y),x, sqrt(x**2 + y**2))) %&gt;%
         select(data,-x,-y) 
</code></pre>

<p><strong>My question: Is there a nicer way to do this using <code>tidyr::gather()</code>?</strong></p>

<p>This would work nicely if not for the diagonal case, where I get multiple rows (obviously because gather is not being told how to handle these cases):</p>

<pre><code>gather(data,direction,separation,x,y, na.rm=T) %&gt;% arrange(t0)
# Source: local data frame [396 x 4]

#             t0         t1 direction    separation
# 1   1449241093 1449241345         y  4.085057e-02
# 2   1449241345 1449241537         y  4.085057e-02
# ...
# 7   1449242375 1449242627         x  4.085057e-02
# 8   1449242627 1449242818         x  4.085057e-02
# ...
# 77  1449245524 1449246079         x  0.000000e+00
# 78  1449245524 1449246079         y  0.000000e+00
# 79  1449246079 1449246101         x -2.042528e-01
# 80  1449246079 1449246101         y -2.042528e-01
# ...
</code></pre>

<p>Basically, what I need is a more advanced version of
<a href="https://stackoverflow.com/questions/28509462/how-to-collapse-many-records-into-one-while-removing-na-values">How to collapse many records into one while removing NA values</a></p>