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閱讀 230,563評論 6 544
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,694評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,672評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,965評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,690評論 6 413
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 56,019評論 1 329
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,013評論 3 449
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,188評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,718評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,438評論 3 360
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,667評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,149評論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,845評論 3 351
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,252評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,590評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,384評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,635評論 2 380

推薦閱讀更多精彩內容