Say I have a data.frame dat
like this one
id X_a X_b Y_a Y_b
v1 -0.012758 0.004537 -0.022725 0.005833
v2 -0.016706 0.003332 -0.006948 0.004965
v3 -0.005629 0.006972 -0.010578 0.006069
I want it to become "gathered". Note that X_a
and X_b
shall be gathered as well as Y_a
and Y_b
. The desired result is:
id X_Y_type X Y
v1 X_Y_a -0.012758 -0.022725
v2 X_Y_a -0.016706 -0.006948
v3 X_Y_a -0.005629 -0.010578
v1 X_Y_b 0.004537 0.005833
v2 X_Y_b 0.003332 0.004965
v3 X_Y_b 0.006972 0.006069
gather()
applied two times is not what I want:
dat %>%
gather(X_type, X, X_a:X_b) %>%
gather(Y_type, Y, Y_a:Y_b)
id X_type X Y_type Y
v1 X_a -0.012758 Y_a -0.022725
v2 X_a -0.016706 Y_a -0.006948
v3 X_a -0.005629 Y_a -0.010578
v1 X_b 0.004537 Y_a -0.022725
v2 X_b 0.003332 Y_a -0.006948
v3 X_b 0.006972 Y_a -0.010578
v1 X_a -0.012758 Y_b 0.005833
v2 X_a -0.016706 Y_b 0.004965
v3 X_a -0.005629 Y_b 0.006069
v1 X_b 0.004537 Y_b 0.005833
v2 X_b 0.003332 Y_b 0.004965
v3 X_b 0.006972 Y_b 0.006069
I want a matching of X_a
to Y_a
and X_b
to Y_b
, so a fake syntax would be
dat %>%
gather(X_type = Y_type, list(X, Y), list(X_a:X_b, Y_a:Y_b))
Any hints?