I have some data regarding separation in x
and y
as a function of time.
There can be a separation only in x
, only in y
, or both (diagonal, with x==y
):
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
# ...
I want to bring this into this format:
# 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
# ...
Currently I'm doing this using code like this:
data %>% 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))) %>%
select(data,-x,-y)
My question: Is there a nicer way to do this using tidyr::gather()
?
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):
gather(data,direction,separation,x,y, na.rm=T) %>% 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
# ...
Basically, what I need is a more advanced version of How to collapse many records into one while removing NA values