WGCNA分析 | 全流程代码分享 | 代码二

--
关于WGNCA的教程,本次的共有三期教程,我们同时做了三个分析的比较,差异性相对还是比较大的,详情可看WGCNA分析 | 你的数据结果真的是准确的吗??,这里面我们只是做了输出图形的比较差异,具体基因的差异尚未做。如果,有同学感兴趣的话,可以自己做一下。

在前面的教程,我们分享了WGCNA分析 | 全流程分析代码 | 代码一,这个教程的代码就是无脑运行即可,只需要你更改你的输入文件名称即可,后续的参数自己进行调整,基本就可以做结束整个WGCNA的分析,以及获得你想要的结果文件。

本次是WGCNA分析 | 全流程分析代码 | 代码二的教程,本次使用的代码输出的结果与上一次的结果文件类型是一致,但是由于各个方面的参数调整,让结果图形也有不同的改变。

此外,本次教程输出结果多增加了各hub基因之间的Link连接信息。这部分信息,可以直接输入Cytoscape软件中,获得hub的网络图


对于这部分数据的输出,参考GitHub中大佬的方法也可以,原理都是一样的。只是本次教程中的代码是批量运行获得全部模块基因的link信息


1. 教程代码

分析所需包的安装

#install.packages("WGCNA")
#BiocManager::install('WGCNA')

library(WGCNA)
options(stringsAsFactors = FALSE)
## 打开多线程
enableWGCNAThreads()

1.1 样本数据的过滤

导入数据及处理

exr1_symbol_no_dup <- read.csv("ExpData_WGCNA.csv",row.names = 1)
dim(exr1_symbol_no_dup)
head(exr1_symbol_no_dup)
colnames(exr1_symbol_no_dup)
#转置
mydata <- exr1_symbol_no_dup
datExpr2 = data.frame(t(exr1_symbol_no_dup))
colnames(datExpr2) <- rownames(mydata)
rownames(datExpr2) <- colnames(mydata)
head(datExpr2)
dim(datExpr2)


注:如果你的数据开始就是这里类型的数据格式,即无需进行的此步骤。

基因过滤

datExpr1<-datExpr2
gsg = goodSamplesGenes(datExpr1, verbose = 3);
gsg$allOK
if (!gsg$allOK){
  # Optionally, print the gene and sample names that were removed:
  if (sum(!gsg$goodGenes)>0) 
    printFlush(paste("Removing genes:", paste(names(datExpr1)[!gsg$goodGenes], collapse = ", ")));
  if (sum(!gsg$goodSamples)>0) 
    printFlush(paste("Removing samples:", paste(rownames(datExpr1)[!gsg$goodSamples], collapse = ", ")));
  # Remove the offending genes and samples from the data:
  datExpr1 = datExpr1[gsg$goodSamples, gsg$goodGenes]
}

绘制样本聚类图

sampleTree = hclust(dist(datExpr1), method = "average")
pdf("1_sample clutering.pdf", width = 6, height = 4)
par(cex = 0.7);
par(mar = c(0,4,2,0))
plot(sampleTree, main = "Sample clustering to detect outliers", sub="", xlab="", cex.lab = 1.5,
     cex.axis = 1.5, cex.main = 2)
dev.off()

1.2 去除离群体

在样本群体中,有一个样本的是较为离散的,需要去除,我们使用过滤掉Height 高于1500的群体。(注意:abline的参数依据你的数据进行设置。

pdf("2_sample clutering_delete_outliers.pdf", width = 8, height = 6)
plot(sampleTree, main = "Sample clustering to detect outliers", sub="", xlab="", cex.lab = 1.5, 
     cex.axis = 1.5, cex.main = 2) + 
  abline(h = 1500, col = "red")  ## abline的参数依据你的数据进行设置
dev.off()
clust = cutreeStatic(sampleTree, cutHeight = 1500, ##cutHeight依据自己的数据设置 
                     minSize = 10)
keepSamples = (clust==1)
datExpr = datExpr1[keepSamples, ]
nGenes = ncol(datExpr)
nSamples = nrow(datExpr)
dim(datExpr)
head(datExpr)
####
datExpr0 <- datExpr

1.3 输入表型数据

############### 载入性状数据## input trait data###############
traitData = read.csv("TraitData.csv",row.names=1)
head(traitData)
allTraits = traitData
dim(allTraits)
names(allTraits)
# 形成一个类似于表达数据的数据框架
fpkmSamples = rownames(datExpr0)
traitSamples =rownames(allTraits)
traitRows = match(fpkmSamples, traitSamples)
datTraits = allTraits[traitRows,]
rownames(datTraits)
collectGarbage()

形成一个类似于表达数据的数据框架

进行二次样本聚类

sampleTree2 = hclust(dist(datExpr), method = "average")
# 
traitColors = numbers2colors(datTraits, signed = FALSE)

绘制聚类图

pdf(file="3_Sample_dendrogram_and_trait_heatmap.pdf",width=8,height=6)
plotDendroAndColors(sampleTree2, traitColors,
                    groupLabels = names(datTraits),
                    main = "Sample dendrogram and trait heatmap",cex.colorLabels = 1.5, cex.dendroLabels = 1, cex.rowText = 2)
dev.off()

2. 筛选软阈值

soft power一直是WGCNA分析中比较重要的参数,在前面的教程中也讲述过soft power值可以选用软件默认为最好的soft power值,也可以我们自己进行筛选。

enableWGCNAThreads()
# Choose a set of soft-thresholding powers
#powers = c(1:30)
powers = c(c(1:10), seq(from = 12, to=30, by=2))
# Call the network topology analysis function
sft = pickSoftThreshold(datExpr, powerVector = powers, verbose = 5)

绘图soft power plot

pdf(file="4_软阈值选择.pdf",width=12,height= 8)
par(mfrow = c(1,2))
cex1 = 0.85
plot(sft$fitIndices[,1], -sign(sft$fitIndices[,3])*sft$fitIndices[,2],
     xlab="Soft Threshold (power)",ylab="Scale Free Topology Model Fit,signed R^2",type="n",
     main = paste("Scale independence"));
text(sft$fitIndices[,1], -sign(sft$fitIndices[,3])*sft$fitIndices[,2],
     labels=powers,cex=cex1,col="red");
# this line corresponds to using an R^2 cut-off of h
abline(h=0.85,col="red")
# Mean connectivity as a function of the soft-thresholding power
plot(sft$fitIndices[,1], sft$fitIndices[,5],
     xlab="Soft Threshold (power)",ylab="Mean Connectivity", type="n",
     main = paste("Mean connectivity"))
text(sft$fitIndices[,1], sft$fitIndices[,5], labels=powers, cex=cex1,col="red")
dev.off()


选择最优的soft power

#softPower =sft$powerEstimate
sft$powerEstimate
softPower = 14

3. 模块可视化

此步耗费较长的时间,敬请等待即可。如果数量较大,建议使用服务器进行分析,不提倡使用的本地进行分析;如果,数据量量较少,本地也可以分析。

net = blockwiseModules(datExpr, power = 6,#手动改power
                       #signed, unsigned
                       TOMType = "signed", minModuleSize = 30,#20, 25 
                       reassignThreshold = 0, mergeCutHeight = 0.25, #mergecutheight 0.25
                       numericLabels = TRUE, pamRespectsDendro = FALSE,
                       saveTOMs = TRUE,maxBlockSize = 20000,
                       saveTOMFileBase = "MyTOM",
                       verbose = 3)
table(net$colors) 

如果你的数据量较大,或是你的电脑配置内存较小时,可能会出现以下这种情况哦!


绘制模块聚类图

mergedColors = labels2colors(net$colors)
table(mergedColors)
pdf(file="5_Dynamic Tree Cut.pdf",width=8,height=6)
plotDendroAndColors(net$dendrograms[[1]], mergedColors[net$blockGenes[[1]]],
                    "Module colors",
                    dendroLabels = FALSE, hang = 0.03,
                    addGuide = TRUE, guideHang = 0.05)
dev.off()

3.1 模块的合并

如果你这里的模块较多,可以使用前面的教程进行模块的合并即可。具体设置,请看WGCNA分析 | 全流程分析代码 | 代码一

# 合并
merge = mergeCloseModules(datExpr0, dynamicColors, cutHeight = MEDissThres, verbose = 3)
# The merged module colors
mergedColors = merge$colors
# Eigengenes of the new merged modules:
mergedMEs = merge$newMEs
table(mergedColors)

#sizeGrWindow(12, 9)
pdf(file="7_merged dynamic.pdf", width = 9, height = 6)
plotDendroAndColors(geneTree, cbind(dynamicColors, mergedColors),
                    c("Dynamic Tree Cut", "Merged dynamic"),
                    dendroLabels = FALSE, hang = 0.03,
                    addGuide = TRUE, guideHang = 0.05)
dev.off()

3.2 输出所有的模块基因

moduleLabels = net$colors
moduleColors = labels2colors(net$colors)
MEs = net$MEs
geneTree = net$dendrograms[[1]]
#输出所有modules

color<-unique(moduleColors)
for (i  in 1:length(color)) {
  y=t(assign(paste(color[i],"expr",sep = "."),datExpr[moduleColors==color[i]]))
  write.csv(y,paste('6',color[i],"csv",sep = "."),quote = F)
}

save.image(file = "module_splitted.RData")
load("module_splitted.RData")

4. 模块和表型数据的相关性热图

## 表型
#samples <- read.csv("TraitData.csv",row.names = 1,header = T)
samples <- traitData
samples <- samples[, -(6:6)]
print(samples)
### ----------------------------------------------------------------------------
##        (最重要的) 模块和性状的关系
moduleLabelsAutomatic <-  net$colors
moduleColorsAutomatic <-  labels2colors(moduleLabelsAutomatic)
moduleColorsWW <-  moduleColorsAutomatic
MEs0 <-  moduleEigengenes(datExpr, moduleColorsWW)$eigengenes
## 赋值,后续可能用得到
moduleColors = moduleColorsWW
####
MEsWW <-  orderMEs(MEs0)
modTraitCor <-  cor(MEsWW, samples, use = "p")
colnames(MEsWW)
###赋值
modlues = MEsWW
#write.csv(modlues,file = "./modules_expr.csv")
modTraitP <-  corPvalueStudent(modTraitCor, nSamples)
textMatrix <- paste(signif(modTraitCor, 2), "\n(", signif(modTraitP, 1), ")", sep = "")
dim(textMatrix) <-  dim(modTraitCor)

绘Module-trait图


详细内容请查看: WGCNA分析 | 全流程分析代码 | 代码二

小杜的生信筆記 ,主要发表或收录生物信息学的教程,以及基于R的分析和可视化(包括数据分析,图形绘制等);分享感兴趣的文献和学习资料!!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 195,783评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,360评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 142,942评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,507评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,324评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,299评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,685评论 3 386
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,358评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,652评论 1 293
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,704评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,465评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,318评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,711评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,991评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,265评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,661评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,864评论 2 335

推荐阅读更多精彩内容