01、02是重点,需着重处理好,后续才能顺利,可形成模版
image.png

安装

  1. options("repos"="https://mirrors.ustc.edu.cn/CRAN/")
  2. if(!require("BiocManager")) install.packages("BiocManager",update = F,ask = F)
  3. options(BioC_mirror="https://mirrors.ustc.edu.cn/bioc/")
  4. cran_packages <- c('tidyr',
  5. 'tibble',
  6. 'dplyr',
  7. 'stringr',
  8. 'ggplot2',
  9. 'ggpubr',
  10. 'factoextra',
  11. 'FactoMineR',
  12. 'devtools',
  13. 'cowplot',
  14. 'patchwork',
  15. 'basetheme',
  16. 'paletteer',
  17. 'AnnoProbe',
  18. 'ggthemes',
  19. 'VennDiagram',
  20. 'tinyarray')
  21. Biocductor_packages <- c('GEOquery',
  22. 'hgu133plus2.db',
  23. 'ggnewscale',
  24. "limma",
  25. "impute",
  26. "GSEABase",
  27. "GSVA",
  28. "clusterProfiler",
  29. "org.Hs.eg.db",
  30. "preprocessCore",
  31. "enrichplot",
  32. "ggplotify")
  33. for (pkg in cran_packages){
  34. if (! require(pkg,character.only=T) ) {
  35. install.packages(pkg,ask = F,update = F)
  36. require(pkg,character.only=T)
  37. }
  38. }
  39. for (pkg in Biocductor_packages){
  40. if (! require(pkg,character.only=T) ) {
  41. BiocManager::install(pkg,ask = F,update = F)
  42. require(pkg,character.only=T)
  43. }
  44. }
  45. #前面的所有提示和报错都先不要管。主要看这里
  46. for (pkg in c(Biocductor_packages,cran_packages)){
  47. require(pkg,character.only=T)
  48. }
  49. #没有任何提示就是成功了,如果有warningxx包不存在,用library检查一下。
  50. #library报错,就单独安装。
  51. library(hgu133plus2.db)

下载及检查数据

  1. #切记先听课再跑代码
  2. #数据下载
  3. rm(list = ls())
  4. library(GEOquery)
  5. #先去网页确定是否是表达芯片数据,不是的话不能用本流程。
  6. #功能参数不需要更改
  7. #getGEO具有判断机制,如果本地有,则不会再下载
  8. gse_number = "GSE56649"
  9. eSet <- getGEO(gse_number, destdir = '.', getGPL = F)
  10. class(eSet)
  11. length(eSet)
  12. eSet = eSet[[1]]
  13. #(1)提取表达矩阵exp
  14. exp <- exprs(eSet)
  15. dim(exp)
  16. exp[1:4,1:4]#列出前44列的情况
  17. #检查矩阵是否正常,如果是空的就会报错。对于空的、负值的、异常值的矩阵需要处理原始数据
  18. #如果表达矩阵为空,大多数是转录组数据,不能用这个流程(后面另讲)。
  19. #自行判断是否需要log。一般数值<20,则取过log;若是几百上千,则未取
  20. exp = log2(exp+1)
  21. boxplot(exp)
  22. #(2)提取临床信息
  23. pd <- pData(eSet)
  24. #(3)让exp列名与pd的行名顺序完全一致
  25. p = identical(rownames(pd),colnames(exp));p
  26. if(!p) exp = exp[,match(rownames(pd),colnames(exp))]
  27. #(4)提取芯片平台编号
  28. gpl_number <- eSet@annotation;gpl_number
  29. save(gse_number,pd,exp,gpl_number,file = "step1output.Rdata")

image.png
image.png
image.png

实验分组&探针注释

  1. # Group(实验分组)和ids(探针注释)
  2. rm(list = ls())
  3. load(file = "step1output.Rdata")
  4. library(stringr)
  5. # 标准流程代码是二分组,多分组数据的分析后面另讲
  6. # 生成Group向量的三种常规方法,三选一,选谁就把第几个逻辑值写成T,另外两个为F。如果三种办法都不适用,可以继续往后写else if
  7. if(F){
  8. # 1.Group----
  9. # 第一种方法,有现成的可以用来分组的列
  10. Group = pd$`disease state:ch1`
  11. }else if(F){
  12. # 第二种方法,自己生成
  13. Group = c(rep("RA",times=13),
  14. rep("control",times=9))
  15. Group = rep(c("RA","control"),times = c(13,9))
  16. }else if(T){
  17. # 第三种方法,使用字符串出理的函数获取分组
  18. Group=ifelse(str_detect(pd$source_name_ch1,"control"),
  19. "control",
  20. "RA")
  21. }
  22. # 需要把Group转换成因子,并设置参考水平,指定levels,对照组在前,处理组在后
  23. Group = factor(Group,levels = c("control","RA"))
  24. Group

探针注释:探针与基因的对应关系

image.png
gpl文件解析
image.png
自主注释流程
image.png
可能存在一个探针对应多个基因
image.png

  1. #2.探针注释的获取-----------------
  2. #捷径
  3. library(tinyarray)
  4. find_anno(gpl_number)
  5. ids <- AnnoProbe::idmap('GPL570')
  6. #四种方法,方法1里找不到就从方法2找,以此类推。
  7. #不同的方法,获取的数值可能有些差异,但被允许
  8. #方法1 BioconductorR包(最常用)
  9. gpl_number
  10. #http://www.bio-info-trainee.com/1399.html
  11. if(!require(hgu133plus2.db))BiocManager::install("hgu133plus2.db")
  12. library(hgu133plus2.db)
  13. ls("package:hgu133plus2.db")
  14. ids <- toTable(hgu133plus2SYMBOL)
  15. head(ids)
  16. # 方法2 读取GPL网页的表格文件,按列取子集
  17. ##https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GPL570
  18. if(F){
  19. #注:表格读取参数、文件列名不统一,活学活用,有的表格里没有symbol列,也有的GPL平台没有提供注释表格
  20. b = read.table("GPL570-55999.txt",header = T,
  21. quote = "\"",sep = "\t",check.names = F)
  22. colnames(b)
  23. ids2 = b[,c("ID","Gene Symbol")] #按列名取子集
  24. colnames(ids2) = c("probe_id","symbol")
  25. ids2 = ids2[ids2$symbol!="" & !str_detect(ids2$symbol,"///"),]
  26. } #去除存在///的探针
  27. # 方法3 官网下载注释文件并读取
  28. ##http://www.affymetrix.com/support/technical/byproduct.affx?product=hg-u133-plus
  29. # 方法4 自主注释
  30. #https://mp.weixin.qq.com/s/mrtjpN8yDKUdCSvSUuUwcA
  31. save(exp,Group,ids,gse_number,file = "step2output.Rdata")

多个探针对应1个基因
image.png
image.png

差异分析图

  1. rm(list = ls())
  2. load(file = "step1output.Rdata")
  3. load(file = "step4output.Rdata")
  4. #1.火山图----
  5. library(dplyr)
  6. library(ggplot2)
  7. dat = deg[!duplicated(deg$symbol),]
  8. p <- ggplot(data = dat,
  9. aes(x = logFC,
  10. y = -log10(P.Value))) +
  11. geom_point(alpha=0.4, size=3.5,
  12. aes(color=change)) +
  13. ylab("-log10(Pvalue)")+
  14. scale_color_manual(values=c("blue", "grey","red"))+
  15. geom_vline(xintercept=c(-logFC_t,logFC_t),lty=4,col="black",lwd=0.8) +
  16. geom_hline(yintercept = -log10(P.Value_t),lty=4,col="black",lwd=0.8) +
  17. theme_bw()
  18. p
  19. for_label <- dat%>%
  20. filter(symbol %in% c("HADHA","LRRFIP1")) #添加指定基因
  21. volcano_plot <- p +
  22. geom_point(size = 3, shape = 1, data = for_label) +
  23. ggrepel::geom_label_repel(
  24. aes(label = symbol),
  25. data = for_label,
  26. color="black"
  27. ) #对数据进行筛选,允许对不同图层进行特定设置
  28. volcano_plot
  29. #2.差异基因热图----
  30. load(file = 'step2output.Rdata')
  31. # 表达矩阵行名替换
  32. exp = exp[dat$probe_id,]
  33. rownames(exp) = dat$symbol
  34. if(F){
  35. #全部差异基因
  36. cg = dat$symbol[dat$change !="stable"]
  37. length(cg)
  38. }else{
  39. #取前10上调和前10下调
  40. library(dplyr)
  41. dat2 = dat %>%
  42. filter(change!="stable") %>%
  43. arrange(logFC)
  44. cg = c(head(dat2$symbol,10),
  45. tail(dat2$symbol,10))
  46. }
  47. n=exp[cg,]
  48. dim(n)
  49. #差异基因热图
  50. library(pheatmap)
  51. annotation_col=data.frame(group=Group)
  52. rownames(annotation_col)=colnames(n)
  53. heatmap_plot <- pheatmap(n,show_colnames =F,
  54. scale = "row",
  55. #cluster_cols = F,
  56. annotation_col=annotation_col,
  57. breaks = seq(-3,3,length.out = 100)
  58. )
  59. heatmap_plot
  60. #拼图
  61. library(patchwork)
  62. library(ggplotify)
  63. volcano_plot +as.ggplot(heatmap_plot)
  64. # 3.感兴趣基因的相关性----
  65. library(corrplot)
  66. g = deg$symbol[1:10] # 换成自己感兴趣的基因
  67. g
  68. M = cor(t(exp[g,]))
  69. pheatmap(M)
  70. library(paletteer)
  71. my_color = rev(paletteer_d("RColorBrewer::RdYlBu"))
  72. my_color = colorRampPalette(my_color)(10)
  73. corrplot(M, type="upper",
  74. method="pie",
  75. order="hclust",
  76. col=my_color,
  77. tl.col="black",
  78. tl.srt=45)
  79. library(cowplot)
  80. cor_plot <- recordPlot()#抠图
  81. # 拼图
  82. load("pca_plot.Rdata")
  83. plot_grid(pca_plot,cor_plot,
  84. volcano_plot,heatmap_plot$gtable)
  85. dev.off()
  86. #保存
  87. pdf("deg.pdf", width = 12,height = 12 )#修改图的大小
  88. plot_grid(pca_plot,cor_plot,
  89. volcano_plot,heatmap_plot$gtable)
  90. dev.off()

主成分分析

image.png
image.png
image.png

  1. rm(list = ls())
  2. load(file = "step1output.Rdata")
  3. load(file = "step2output.Rdata")
  4. #输入数据:exp和Group
  5. #Principal Component Analysis
  6. #http://www.sthda.com/english/articles/31-principal-component-methods-in-r-practical-guide/112-pca-principal-component-analysis-essentials
  7. # 1.PCA 图----
  8. dat=as.data.frame(t(exp))
  9. library(FactoMineR)
  10. library(factoextra)
  11. dat.pca <- PCA(dat, graph = FALSE)
  12. pca_plot <- fviz_pca_ind(dat.pca,
  13. geom.ind = "point", # show points only (nbut not "text")
  14. col.ind = Group, # color by groups
  15. palette = c("#00AFBB", "#E7B800"),
  16. addEllipses = TRUE, # Concentration ellipses
  17. legend.title = "Groups"
  18. )
  19. pca_plot
  20. save(pca_plot,file = "pca_plot.Rdata")
  21. # 2.top 1000 sd 热图----
  22. cg=names(tail(sort(apply(exp,1,sd)),1000))
  23. n=exp[cg,]
  24. # 直接画热图,对比不鲜明
  25. library(pheatmap)
  26. annotation_col=data.frame(group=Group) #指示条
  27. rownames(annotation_col)=colnames(n)
  28. pheatmap(n,
  29. show_colnames =F,
  30. show_rownames = F,
  31. annotation_col=annotation_col
  32. )
  33. # 按行标准化
  34. pheatmap(n,
  35. show_colnames =F,
  36. show_rownames = F,
  37. annotation_col=annotation_col,
  38. scale = "row", #实现标准化
  39. breaks = seq(-3,3,length.out = 100) #设置色带
  40. )
  41. dev.off()
  42. # 关于scale的进一步学习:zz.scale.R

DEG差异分析、可视化

  1. rm(list = ls())
  2. load(file = "step2output.Rdata")
  3. #差异分析,用limma包来做
  4. #需要表达矩阵和Group,不需要改
  5. library(limma)
  6. design=model.matrix(~Group)
  7. fit=lmFit(exp,design)
  8. fit=eBayes(fit)
  9. deg=topTable(fit,coef=2,number = Inf)
  10. #为deg数据框添加几列
  11. #1.加probe_id列,把行名变成一列
  12. library(dplyr)
  13. deg <- mutate(deg,probe_id=rownames(deg))
  14. #2.加上探针注释
  15. ids = ids[!duplicated(ids$symbol),] #随机去重
  16. #其他去重方式在zz.去重方式.R
  17. deg <- inner_join(deg,ids,by="probe_id")
  18. nrow(deg)
  19. #3.加change列,标记上下调基因
  20. logFC_t=1
  21. P.Value_t = 0.05
  22. k1 = (deg$P.Value < P.Value_t)&(deg$logFC < -logFC_t)
  23. k2 = (deg$P.Value < P.Value_t)&(deg$logFC > logFC_t)
  24. deg <- mutate(deg,change = ifelse(k1,"down",ifelse(k2,"up","stable")))
  25. table(deg$change)
  26. #4.加ENTREZID列,用于富集分析(symbol转entrezid,然后inner_join)
  27. library(clusterProfiler)
  28. library(org.Hs.eg.db)
  29. s2e <- bitr(deg$symbol,
  30. fromType = "SYMBOL",
  31. toType = "ENTREZID",
  32. OrgDb = org.Hs.eg.db)#人类
  33. #其他物种http://bioconductor.org/packages/release/BiocViews.html#___OrgDb
  34. deg <- inner_join(deg,s2e,by=c("symbol"="SYMBOL"))
  35. save(Group,deg,logFC_t,P.Value_t,gse_number,file = "step4output.Rdata")

富集分析(GSEA)

  1. rm(list = ls())
  2. load(file = 'step4output.Rdata')
  3. library(clusterProfiler)
  4. library(ggthemes)
  5. library(org.Hs.eg.db)
  6. library(dplyr)
  7. library(ggplot2)
  8. library(stringr)
  9. library(enrichplot)
  10. # 1.GO 富集分析----
  11. #(1)输入数据
  12. gene_up = deg$ENTREZID[deg$change == 'up']
  13. gene_down = deg$ENTREZID[deg$change == 'down']
  14. gene_diff = c(gene_up,gene_down)
  15. #(2)富集
  16. #以下步骤耗时很长,设置了存在即跳过
  17. if(!file.exists(paste0(gse_number,"_GO.Rdata"))){
  18. ego <- enrichGO(gene = gene_diff,
  19. OrgDb= org.Hs.eg.db,
  20. ont = "ALL",
  21. readable = TRUE)
  22. ego_BP <- enrichGO(gene = gene_diff,
  23. OrgDb= org.Hs.eg.db,
  24. ont = "BP",
  25. readable = TRUE)
  26. #ont参数:One of "BP", "MF", and "CC" subontologies, or "ALL" for all three.
  27. save(ego,ego_BP,file = paste0(gse_number,"_GO.Rdata"))
  28. }
  29. load(paste0(gse_number,"_GO.Rdata"))
  30. #(3)可视化
  31. #条带图
  32. barplot(ego)
  33. barplot(ego, split = "ONTOLOGY", font.size = 10,
  34. showCategory = 5) +
  35. facet_grid(ONTOLOGY ~ ., space = "free_y",scales = "free_y")
  36. #气泡图
  37. dotplot(ego)
  38. dotplot(ego, split = "ONTOLOGY", font.size = 10,
  39. showCategory = 5) +
  40. facet_grid(ONTOLOGY ~ ., space = "free_y",scales = "free_y")
  41. #(3)展示top通路的共同基因,要放大看。
  42. #gl 用于设置下图的颜色
  43. gl = deg$logFC
  44. names(gl)=deg$ENTREZID
  45. #Gene-Concept Network
  46. cnetplot(ego,categorySize="pvalue", foldChange=gl,colorEdge = TRUE,showCategory = 3)
  47. cnetplot(ego, showCategory = 3,foldChange=gl, circular = TRUE, colorEdge = TRUE)
  48. # 2.KEGG pathway analysis----
  49. #上调、下调、差异、所有基因
  50. #(1)输入数据
  51. gene_up = deg[deg$change == 'up','ENTREZID']
  52. gene_down = deg[deg$change == 'down','ENTREZID']
  53. gene_diff = c(gene_up,gene_down)
  54. #(2)对上调/下调/所有差异基因进行富集分析
  55. if(!file.exists(paste0(gse_number,"_KEGG.Rdata"))){
  56. kk.up <- enrichKEGG(gene = gene_up,
  57. organism = 'hsa')
  58. kk.down <- enrichKEGG(gene = gene_down,
  59. organism = 'hsa')
  60. kk.diff <- enrichKEGG(gene = gene_diff,
  61. organism = 'hsa')
  62. save(kk.diff,kk.down,kk.up,file = paste0(gse_number,"_KEGG.Rdata"))
  63. }
  64. load(paste0(gse_number,"_KEGG.Rdata"))
  65. #(3)看看富集到了吗?https://mp.weixin.qq.com/s/NglawJgVgrMJ0QfD-YRBQg
  66. table(kk.diff@result$p.adjust<0.05)
  67. table(kk.up@result$p.adjust<0.05)
  68. table(kk.down@result$p.adjust<0.05)
  69. #(4)双向图
  70. # 富集分析所有图表默认都是用p.adjust,富集不到可以退而求其次用p值,在文中说明即可
  71. down_kegg <- kk.down@result %>%
  72. filter(pvalue<0.05) %>% #筛选行
  73. mutate(group=-1) #新增列
  74. up_kegg <- kk.up@result %>%
  75. filter(pvalue<0.05) %>%
  76. mutate(group=1)
  77. source("kegg_plot_function.R")
  78. g_kegg <- kegg_plot(up_kegg,down_kegg)
  79. g_kegg
  80. #g_kegg +scale_y_continuous(labels = c(2,0,2,4,6))
  81. # 3.GSEA作kegg和GO富集分析----
  82. #https://www.yuque.com/xiaojiewanglezenmofenshen/dbwkg1/ytawgg
  83. #(1)查看示例数据
  84. data(geneList, package="DOSE")
  85. #(2)将我们的数据转换成示例数据的格式
  86. geneList=deg$logFC
  87. names(geneList)=deg$ENTREZID
  88. geneList=sort(geneList,decreasing = T)
  89. #(3)GSEA富集
  90. kk_gse <- gseKEGG(geneList = geneList,
  91. organism = 'hsa',
  92. verbose = FALSE)
  93. down_kegg<-kk_gse[kk_gse$pvalue<0.05 & kk_gse$enrichmentScore < 0,];down_kegg$group=-1
  94. up_kegg<-kk_gse[kk_gse$pvalue<0.05 & kk_gse$enrichmentScore > 0,];up_kegg$group=1
  95. #(4)可视化
  96. g2 = kegg_plot(up_kegg,down_kegg)
  97. g2
  98. # 4.能看懂的资料越来越多----
  99. # GSEA学习更多:https://www.yuque.com/docs/share/a67a180f-dd2b-4f6f-96c2-68a4b86fe862?#
  100. # 富集分析学习更多:http://yulab-smu.top/clusterProfiler-book/index.html
  101. # 弦图:https://www.yuque.com/xiaojiewanglezenmofenshen/dbwkg1/dgs65p
  102. # GOplot:https://mp.weixin.qq.com/s/LonwdDhDn8iFUfxqSJ2Wew
  103. # 网上的资料和宝藏无穷无尽,学好R语言慢慢发掘~
  1. if(F){
  2. a = 1 #限速步骤
  3. save(a,file = "a.Rdata")
  4. }
  5. load("a.Rdata")
  6. if(!file.exists("a.Rdata")){
  7. a = 1 #限速步骤
  8. save(a,file = "a.Rdata")
  9. }
  10. load("a.Rdata")

问题和解答

image.png

image.png