长矩阵变成宽矩阵

如果是简单的转换问题,我们的生信技能树: 生信编程直播第四题:多个同样的行列式文件合并起来 里面详细讲解了这个操作:http://www.biotrainee.com/thread-603-1-1.html 

对表达矩阵来说,一个基因在一个样本里面,肯定只有一个表达量的,即使该基因有多个探针,我们一般也会选取某个探针来代表这个基因。当然了,如何选取,也是有学问的,而且也很考验代码技术。比如技能树的,多个探针对应一个基因,取平均值该怎么写:http://www.biotrainee.com/thread-2077-1-1.html

但是对CNV来说,一个基因可能是有多个值的,类似于针对同一个基因设计的多个探针的表达量不一致一样,如果简单的去整合转换,通常会报错。

核心代码

如果你的理解力还不错,看下面代码即可:

library(tidyr)
options(stringsAsFactors = F)
df=data.frame(sample=rep(LETTERS[1:3],each=3),
              value=runif(9),
              genes=rep(LETTERS[1:3],3) 
              )
df=rbind(df,c('A',5,'A'))
print(df)
df$value=as.numeric(df$value)
colnames(df)=c('sample','value','genes') 
spread(df,'genes','value')
library(data.table) ## v >= 1.9.6
 dcast(setDT(df),  genes ~ sample, fun.aggregate = mean )  
​

我虚拟了一个数据,如下;

> df
   sample             value genes
1       A 0.258136499440297     A
2       A 0.602033647475764     B
3       A  0.43506146944128     C
4       B 0.818765353877097     A
5       B 0.870608947239816     B
6       B 0.844981355592608     C
7       C 0.965881496202201     A
8       C 0.785905135096982     B
9       C 0.170834832359105     C
10      A                 5     A

很明显,A基因在A样本里面,有两个值,所以导致 简单的转换失败。

报错如下;

Error: Duplicate identifiers for rows (1, 10)

简单谷歌就找到了以上解决方案,:https://stackoverflow.com/questions/30592094/r-spreading-multiple-columns-with-tidyr

Comments are closed.