如何在R中融化多列

时间:2018-06-30 22:25:53

标签: r melt

我将此数据称为my.data。我想将所有列融合在一起,并在三列中得到结果。最终数据应包含三列-

1. key.related column
2. IBS values from all three columns (IBS_2_samples IBS_4_samples IBS_8_samples)
3. Column indicating IBS columns types (i.e, column values should be IBS_2_samples IBS_4_samples IBS_8_samples accordingly).

请教我如何融合这些数据,以便可以用它绘制线图(如下所示:Plot multiple lines (data series) each with unique color in R)。谢谢

my.data<- structure(list(key.related = c("G11F:G11F", "G11M:G11M", "G29P:G29P", 
"G29P:G29S"), IBS_2_samples = c(0.533, 0.629, NA, NA), IBS_4_samples = c(1.01, 
1.04, 0.83, 0.349), IBS_8_samples = c(1.11, 1.11, 0.956, 0.42
)), .Names = c("key.related", "IBS_2_samples", "IBS_4_samples", 
"IBS_8_samples"), row.names = c(NA, 4L), class = "data.frame")

1 个答案:

答案 0 :(得分:0)

您可以使用data.table::melt将长格式的数据转换为:

library(data.table)

melt(setDT(my.data),id.vars = "key.related")

#    key.related      variable value
# 1:   G11F:G11F IBS_2_samples 0.533
# 2:   G11M:G11M IBS_2_samples 0.629
# 3:   G29P:G29P IBS_2_samples    NA
# 4:   G29P:G29S IBS_2_samples    NA
# 5:   G11F:G11F IBS_4_samples 1.010
# 6:   G11M:G11M IBS_4_samples 1.040
# 7:   G29P:G29P IBS_4_samples 0.830
# 8:   G29P:G29S IBS_4_samples 0.349
# 9:   G11F:G11F IBS_8_samples 1.110
# 10:   G11M:G11M IBS_8_samples 1.110
# 11:   G29P:G29P IBS_8_samples 0.956
# 12:   G29P:G29S IBS_8_samples 0.420