DEGs
library(GEOquery)
library(Biobase)
library(affy)
library(BiocGenerics)
library(dplyr)
library(tidyverse)
library(limma)
library(pheatmap)
library(affyPLM)
library(affy)
a=read.table('GSEXXX_series_matrix.txt.gz',sep='\t',fill = T,comment.char = "!",header = T)
rownames(a)=a[,1]
a1=a[,-1]
b=getGEO(filename ='GSEXXX_family.soft.gz')
b1=b@gpls[["GPLXX"]]@dataTable@table
ex <- a1
qx <- as.numeric(quantile(ex, c(0., 0.25, 0.5, 0.75, 0.99, 1.0), na.rm=T))
LogC <- (qx[5] > 100) ||
  (qx[6]-qx[1] > 50 && qx[2] > 0) ||
  (qx[2] > 0 && qx[2] < 1 && qx[4] > 1 && qx[4] < 2)

if (LogC) { ex[which(ex <= 0)] <- NaN
a1 <- log2(ex)
print("log2 transform finished")}else{print("log2 transform not needed")}
b2=b1[,c(1,11)]
names(b2)=c("ID","GENE_SYMBOLl")
explan1 = data.frame(a1)
explan1$ID = rownames(explan1)
explan_symbol = merge(explan1,b2,by="ID")
explan_symbol$GENE_SYMBOL = data.frame(sapply(explan_symbol$GENE_SYMBOL,function(x)unlist(strsplit(x,'///'))[1]),stringsAsFactors = F)[,1]
table(duplicated(explan_symbol$GENE_SYMBOL))
explan_symbol[explan_symbol==""]<-NA
explan_symbol<-na.omit(explan_symbol)
table(duplicated(explan_symbol$GENE_SYMBOL))
c1 <- avereps(explan_symbol[,-c(1,ncol(explan_symbol))],ID=explan_symbol$GENE_SYMBOL)
table(duplicated(rownames(c1)))
write.table(c1,"DEGs.txt",sep="\t",col.names=T,quote=F)

limma
rt=read.table("combat.exp.txt",sep="\t",header=T,check.names=F)
rt=as.matrix(rt)
rownames(rt)=rt[,1]
exp=rt[,2:ncol(rt)]
dimnames=list(rownames(exp),colnames(exp))
rt=matrix(as.numeric(as.matrix(exp)),nrow=nrow(exp),dimnames=dimnames)#？？？？
rt=avereps(rt)
rt1=normalizeBetweenArrays(as.matrix(rt))
cols=rainbow(ncol(rt1)) 
par(cex = 0.3)
if(ncol(rt1)>10) par(cex = 0.3)
pdf(file = "nor1.pdf",width=5,height = 6)
boxplot(rt1,las=2,col =cols ) 
dev.off()
data=rt1
is.numeric(rt1) 
is.numeric(rt1) 
afcon=48
conData=data[,as.vector(colnames(data)[1:afcon])]
aftreat=afcon+1
treatData=data[,as.vector(colnames(data)[aftreat:ncol(data)])]
rt1=cbind(conData,treatData)
is.numeric(rt1)
is.numeric(rt1)
conNum=ncol(conData)
treatNum=ncol(treatData)
Type=c(rep("con",conNum),rep("treat",treatNum))
design <- model.matrix(~0+factor(Type))
colnames(design) <- c("con","treat")
fit <- lmFit(rt1,design)
cont.matrix<-makeContrasts(treat-con,levels=design)
fit2 <- contrasts.fit(fit, cont.matrix)
fit2 <- eBayes(fit2)
Diff=topTable(fit2,adjust='fdr',number=length(rownames(data)))
DIFFOUT=rbind(id=colnames(Diff),Diff)
write.table(DIFFOUT,file="DIFF_all.xls",sep="\t",quote=F,col.names=F)
write.table(DIFFOUT,file="DIFF_all.txt",sep="\t",quote=F,col.names=F)

Immune infiltration analysis
library(vioplot)
library(limma)  
library(e1071)
library(preprocessCore)
library(parallel)
source("CIBERSORT.R")
exp=read.table("XXXX.txt",sep="\t",header=T,check.names=F)
any(is.na(exp))
pmap<-na.omit(exp)
write.table(pmap,"combat.exp.txt",sep="\t")
exp=pmap
exp=read.table("combat.exp.txt",sep="\t",header=T,check.names=F)
results=CIBERSORT("LM22.txt", "combat.exp.txt", perm=100, QN=TRUE)
write.table(results,"a.txt")
pkgs <- c("matrixStats", "pheatmap", "RColorBrewer", "tidyverse", "cowplot","ggpubr","bslib","ggthemes")
lapply(pkgs, library, character.only = T)
Ctrl=24
AS=19
rt=read.table("CIBERSORT-Results.txt",sep = "\t",header = T,row.names = 1,check.names = F)
pdf("vioplot.pdf",height = 8,width = 15)
par(las=1,mar=c(10,6,3,3))
x=c(1:ncol(rt))
y=c(1:ncol(rt))
plot(x,y,
     xlim=c(0,63),ylim=c(min(rt),max(rt)+0.02),
     main="",xlab="",ylab="Fraction",
     pch=21,
     col="white",
     xaxt="n")
for (i in 1:ncol(rt)){
  HighData=rt[1:Ctrl,i]
  LowData=rt[(Ctrl+1):(Ctrl+AS),i]
  vioplot(HighData,at=3*(i-1),lty=1,add=T,col="blue")
  vioplot(LowData,at=3*(i-1)+1,lty=1,add=T,col="red")
  wilcoxTest=wilcox.test(HighData,LowData,exact=FALSE)
  p=round(wilcoxTest$p.value,3)
  mx=max(c(HighData,LowData))
  lines(c(x=3*(i-1)+0.2,x=3*(i-1)+0.8),c(mx,mx))
  text(x=3*(i-1)+0.5,y=mx+0.02,labels=ifelse(p<0.05,paste0("p<0.05"),paste0("p=",p)),cex=0.8)
  text(seq(1,64,3),-0.05,xpd=NA,labels=colnames(rt),cex=1,srt=45,pos=2)
}
dev.off()

WGCNA
library(limma)
library(gplots)
library(WGCNA)

expFile="normalize.txt"      #?????????ļ?
rt=read.table(expFile, header=T, sep="\t", check.names=F)
rt=as.matrix(rt)
rownames(rt)=rt[,1]
exp=rt[,2:ncol(rt)]
dimnames=list(rownames(exp),colnames(exp))
data=matrix(as.numeric(as.matrix(exp)),nrow=nrow(exp),dimnames=dimnames)
data=avereps(data)
selectGenes=names(tail(sort(apply(data,1,sd)), n=round(nrow(data)*0.25)))
data=data[selectGenes,]
Type=gsub("(.*)\\_(.*)", "\\2", colnames(data))
conCount=length(Type[Type=="Control"])
treatCount=length(Type[Type=="Treat"])
datExpr0=t(data)
gsg = goodSamplesGenes(datExpr0, verbose = 3)
if (!gsg$allOK){
  # Optionally, print the gene and sample names that were removed:
  if (sum(!gsg$goodGenes)>0)
    printFlush(paste("Removing genes:", paste(names(datExpr0)[!gsg$goodGenes], collapse = ", ")))
  if (sum(!gsg$goodSamples)>0)
    printFlush(paste("Removing samples:", paste(rownames(datExpr0)[!gsg$goodSamples], collapse = ", ")))
  # Remove the offending genes and samples from the data:
  datExpr0 = datExpr0[gsg$goodSamples, gsg$goodGenes]
}
sampleTree = hclust(dist(datExpr0), method = "average")
pdf(file = "01.sample_cluster.pdf", width = 12, height = 9)
par(cex = 0.6)
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)
abline(h = 20000, col="red")
dev.off()
clust=cutreeStatic(sampleTree, cutHeight=20000, minSize=10)
table(clust)
keepSamples=(clust==1)
datExpr0=datExpr0[keepSamples,]
traitData=data.frame(Con=c(rep(1,conCount),rep(0,treatCount)),
                     Treat=c(rep(0,conCount),rep(1,treatCount)))
row.names(traitData)=colnames(data)
fpkmSamples=rownames(datExpr0)
traitSamples=rownames(traitData)
sameSample=intersect(fpkmSamples,traitSamples)
datExpr0=datExpr0[sameSample,]
datTraits=traitData[sameSample,]
sampleTree2 = hclust(dist(datExpr0), method="average")
traitColors = numbers2colors(datTraits, signed = FALSE)
pdf(file="02.sample_heatmap.pdf", width=12, height=12)
plotDendroAndColors(sampleTree2, traitColors,
                    groupLabels = names(datTraits),
                    main = "Sample dendrogram and trait heatmap")
dev.off()
enableWGCNAThreads()   #???̹߳???
powers = c(1:20)       #??ָ????Χ1:20
sft = pickSoftThreshold(datExpr0, powerVector = powers, verbose = 5)
pdf(file="03.scale_independence.pdf",width=9,height=5)
par(mfrow = c(1,2))
cex1 = 0.9
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");
abline(h=0.90,col="red") #?????޸?
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()
sft #?鿴????powerֵ
softPower =sft$powerEstimate     #????powerֵ
adjacency = adjacency(datExpr0, power = softPower)
softPower
TOM = TOMsimilarity(adjacency)
dissTOM = 1-TOM
geneTree = hclust(as.dist(dissTOM), method = "average");
pdf(file="04.gene_clustering.pdf",width=12,height=9)
plot(geneTree, xlab="", sub="", main = "Gene clustering on TOM-based dissimilarity",
     labels = FALSE, hang = 0.04)
dev.off()
minModuleSize = 100      #ģ????????Ŀ
dynamicMods = cutreeDynamic(dendro = geneTree, distM = dissTOM,
                            deepSplit = 2, pamRespectsDendro = FALSE,
                            minClusterSize = minModuleSize);
table(dynamicMods)
dynamicColors = labels2colors(dynamicMods)
table(dynamicColors)
pdf(file="05.Dynamic_Tree.pdf",width=8,height=6)
plotDendroAndColors(geneTree, dynamicColors, "Dynamic Tree Cut",
                    dendroLabels = FALSE, hang = 0.03,
                    addGuide = TRUE, guideHang = 0.05,
                    main = "Gene dendrogram and module colors")
dev.off()
MEList = moduleEigengenes(datExpr0, colors = dynamicColors)
MEs = MEList$eigengenes
MEDiss = 1-cor(MEs);
METree = hclust(as.dist(MEDiss), method = "average")
pdf(file="06.Clustering_module.pdf",width=7,height=6)
plot(METree, main = "Clustering of module eigengenes",
     xlab = "", sub = "")
dev.off()
moduleColors=dynamicColors
nGenes = ncol(datExpr0)
nSamples = nrow(datExpr0)
select = sample(nGenes, size=1000)      #????ѡ?????????п??ӻ?
selectTOM = dissTOM[select, select];
selectTree = hclust(as.dist(selectTOM), method="average")
selectColors = moduleColors[select]
#sizeGrWindow(9,9)
plotDiss=selectTOM^softPower
diag(plotDiss)=NA
myheatcol = colorpanel(250, "red", "orange", "lemonchiffon")    #??????ͼ??ɫ(??pdf(file="07.TOMplot.pdf", width=7, height=7)
TOMplot(plotDiss, selectTree, selectColors, main = "Network heatmap plot, selected genes", col=myheatcol)
dev.off()
moduleTraitCor = cor(MEs, datTraits, use = "p")
moduleTraitPvalue = corPvalueStudent(moduleTraitCor, nSamples)
pdf(file="08.Module_trait.pdf", width=6.5, height=5.5)
textMatrix = paste(signif(moduleTraitCor, 2), "\n(",
                   signif(moduleTraitPvalue, 1), ")", sep = "")
dim(textMatrix) = dim(moduleTraitCor)
par(mar = c(3.5, 8, 3, 3))
labeledHeatmap(Matrix = moduleTraitCor,
               xLabels = names(datTraits),
               yLabels = names(MEs),
               ySymbols = names(MEs),
               colorLabels = FALSE,
               colors = blueWhiteRed(50),
               textMatrix = textMatrix,
               setStdMargins = FALSE,
               cex.text = 0.7,
               zlim = c(-1,1),
               main = paste("Module-trait relationships"))
dev.off()
modNames = substring(names(MEs), 3)
geneModuleMembership = as.data.frame(cor(datExpr0, MEs, use = "p"))
MMPvalue = as.data.frame(corPvalueStudent(as.matrix(geneModuleMembership), nSamples))
names(geneModuleMembership) = paste("MM", modNames, sep="")
names(MMPvalue) = paste("p.MM", modNames, sep="")
traitNames=names(datTraits)
geneTraitSignificance = as.data.frame(cor(datExpr0, datTraits, use = "p"))
GSPvalue = as.data.frame(corPvalueStudent(as.matrix(geneTraitSignificance), nSamples))
names(geneTraitSignificance) = paste("GS.", traitNames, sep="")
names(GSPvalue) = paste("p.GS.", traitNames, sep="")
trait="Treat"
traitColumn=match(trait,traitNames)  
for (module in modNames){
	column = match(module, modNames)
	moduleGenes = moduleColors==module
	if (nrow(geneModuleMembership[moduleGenes,]) > 1){
	    outPdf=paste("09.", trait, "_", module,".pdf",sep="")
	    pdf(file=outPdf,width=7,height=7)
	    par(mfrow = c(1,1))
	    verboseScatterplot(abs(geneModuleMembership[moduleGenes, column]),
	                         abs(geneTraitSignificance[moduleGenes, traitColumn]),
	                         xlab = paste("Module Membership in", module, "module"),
	                         ylab = paste("Gene significance for ",trait),
	                         main = paste("Module membership vs. gene significance\n"),
	                         cex.main = 1.2, cex.lab = 1.2, cex.axis = 1.2, col = module)
	    abline(v=0.8,h=0.5,col="red")
	    dev.off()
	}
}
probes = colnames(datExpr0)
geneInfo0 = data.frame(probes= probes,
                       moduleColor = moduleColors)
for (Tra in 1:ncol(geneTraitSignificance))
{
  oldNames = names(geneInfo0)
  geneInfo0 = data.frame(geneInfo0, geneTraitSignificance[,Tra],
                         GSPvalue[, Tra])
  names(geneInfo0) = c(oldNames,names(geneTraitSignificance)[Tra],
                       names(GSPvalue)[Tra])
}

for (mod in 1:ncol(geneModuleMembership))
{
  oldNames = names(geneInfo0)
  geneInfo0 = data.frame(geneInfo0, geneModuleMembership[,mod],
                         MMPvalue[, mod])
  names(geneInfo0) = c(oldNames,names(geneModuleMembership)[mod],
                       names(MMPvalue)[mod])
}
geneOrder =order(geneInfo0$moduleColor)
geneInfo = geneInfo0[geneOrder, ]
write.table(geneInfo, file = "GS_MM.xls",sep="\t",row.names=F)
for (mod in 1:nrow(table(moduleColors))){  
  modules = names(table(moduleColors))[mod]
  probes = colnames(datExpr0)
  inModule = (moduleColors == modules)
  modGenes = probes[inModule]
  write.table(modGenes, file =paste0("module_",modules,".txt"),sep="\t",row.names=F,col.names=F,quote=F)
}
geneSigFilter=0.5         #??????Ҫ?ԵĹ???????
moduleSigFilter=0.8       #??????ģ???????ԵĹ???????
datMM=cbind(geneModuleMembership, geneTraitSignificance)
datMM=datMM[abs(datMM[,ncol(datMM)])>geneSigFilter,]
for(mmi in colnames(datMM)[1:(ncol(datMM)-2)]){
	dataMM2=datMM[abs(datMM[,mmi])>moduleSigFilter,]
	write.table(row.names(dataMM2), file =paste0("hubGenes_",mmi,".txt"),sep="\t",row.names=F,col.names=F,quote=F)
}


