I have the following R data.table (though this should scale with a data.frame too). The goal is to reshape this data.table to plot as a scatterplot in ggplot2
. I therefore need to reshape this data.table to have one "factor" column to color the points:
> library(data.table)
> dt
ID x_A y_A x_B y_B
1: 05AC 0.81 3 0.92 2.05
2: 01BA 0.41 5 0.63 1.8
3: Z1AC 0.41 5 0.58 1.8
4: B2BA 0.21 6.5 1.00 1.8
....
I believe the correct output needs to be of the form:
ID type x y
05AC A 0.81 3
05AC B 0.92 2.05
01BA A 0.41 5
01BA B 0.63 1.8
Z1AC A 0.41 5
Z1AC B 0.58 1.8
B2BA A 0.21 6.5
B2BA B 1.00 1.8
Is there a standard way to "unfold" data.tables in this fashion? I'm happy for how to use dplyr in this case, but I suspect there should be a data.table method.
melt()
would work, if I could figure out how to create the column type
, e.g.
melt(dt, id.vars=c("ID"))
will only melt based on the one column ID
I'm especially confused how one "scrapes" the A and B type from columns 2-3 and columns 4-5 respectively...