reshape2包melt函数对数据进行整合,比较常见的就是利用ggplot2包进行图片绘制的过程中往往需要对数据进行整合,melt()的使用方法如下:
加载R包以及案例数据
library('reshape2')
dat
type sample1 sample2 sample1 sample2
1 A 6.332968 5.367671 5.171107 5.533754
2 A 9.368328 7.286253 6.232718 6.152393
3 B 6.674348 5.217053 5.320568 6.113618
4 B 4.127901 3.875520 4.924498 4.960935
5 C 5.192845 6.679444 7.140883 5.959568
6 C 6.652865 6.127819 4.228142 5.078903
7 D 7.829350 5.091166 5.793514 4.871103
8 D 6.995062 7.942029 6.347785 5.223206
默认参数会将相同类型的数据都整合
melt(dat)
Using type as id variables
type variable value
1 A sample1 6.332968
2 A sample1 9.368328
3 B sample1 6.674348
4 B sample1 4.127901
5 C sample1 5.192845
6 C sample1 6.652865
7 D sample1 7.829350
8 D sample1 6.995062
9 A sample2 5.367671
10 A sample2 7.286253
11 B sample2 5.217053
12 B sample2 3.875520
13 C sample2 6.679444
14 C sample2 6.127819
15 D sample2 5.091166
16 D sample2 7.942029
17 A sample1 6.332968
18 A sample1 9.368328
19 B sample1 6.674348
20 B sample1 4.127901
21 C sample1 5.192845
22 C sample1 6.652865
23 D sample1 7.829350
24 D sample1 6.995062
25 A sample2 5.367671
26 A sample2 7.286253
27 B sample2 5.217053
28 B sample2 3.875520
29 C sample2 6.679444
30 C sample2 6.127819
31 D sample2 5.091166
32 D sample2 7.942029
指定进行整合的列(选择出不进行整合的列),例如第一个样品数据不进行整合,id 也可以写成var.ids
melt(dat,id=c("type","sample1"))
type sample1 variable value
1 A 6.332968 sample2 5.367671
2 A 9.368328 sample2 7.286253
3 B 6.674348 sample2 5.217053
4 B 4.127901 sample2 3.875520
5 C 5.192845 sample2 6.679444
6 C 6.652865 sample2 6.127819
7 D 7.829350 sample2 5.091166
8 D 6.995062 sample2 7.942029
给合并之后的列进行命名,合并的变量variable.name ,以及变量值value.name
melt(dat,id=c("type","sample1"),variable.name = "Samples",value.name = "Expression")
type sample1 Samples Expression
1 A 6.332968 sample2 5.367671
2 A 9.368328 sample2 7.286253
3 B 6.674348 sample2 5.217053
4 B 4.127901 sample2 3.875520
5 C 5.192845 sample2 6.679444
6 C 6.652865 sample2 6.127819
7 D 7.829350 sample2 5.091166
8 D 6.995062 sample2 7.942029
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!