Last updated: 2019-10-28

Checks: 6 1

Knit directory: fgf_alldata/

This reproducible R Markdown analysis was created with workflowr (version 1.4.0). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.

The global environment had objects present when the code in the R Markdown file was run. These objects can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment. Use wflow_publish or wflow_build to ensure that the code is always run in an empty environment.

The following objects were defined in the global environment when these results were created:

Name Class Size
data environment 56 bytes
env environment 56 bytes

The command set.seed(20191021) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility. The version displayed above was the version of the Git repository at the time these results were generated.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Ignored files:
    Ignored:    .Rproj.user/
    Ignored:    test_files/

Untracked files:
    Untracked:  code/sc_functions.R
    Untracked:  data/fgf_filtered_nuclei.RDS
    Untracked:  data/filtglia.RDS
    Untracked:  data/glia/
    Untracked:  data/lps1.txt
    Untracked:  data/mcao1.txt
    Untracked:  data/mcao_d3.txt
    Untracked:  data/mcaod7.txt
    Untracked:  data/neur_astro_induce.xlsx
    Untracked:  data/neuron/
    Untracked:  data/synaptic_activity_induced.xlsx
    Untracked:  docs/figure/
    Untracked:  olig_ttest_padj.csv
    Untracked:  output/agrp_pcgenes.csv
    Untracked:  output/all_wc_markers.csv
    Untracked:  output/allglia_wgcna_genemodules.csv
    Untracked:  output/glia/
    Untracked:  output/glial_markergenes.csv
    Untracked:  output/integrated_all_markergenes.csv
    Untracked:  output/integrated_neuronmarkers.csv
    Untracked:  output/neuron/

Unstaged changes:
    Modified:   analysis/8_astro_wgcna.Rmd

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


There are no past versions. Publish this analysis with wflow_publish() to start tracking its development.


Load Libraries

library(Seurat)
library(DESeq2)
library(future.apply)
library(cowplot)
library(tidyverse)
library(ggrepel)
library(reshape2)
library(ggpubr)
library(here)
library(wesanderson)
library(ggupset)
library(ggcorrplot)
library(gProfileR)
plan(multiprocess, workers=40)
options(future.globals.maxSize = 4000 * 1024^2)

Functions

source(here("code/sc_functions.R"))

Generate Glial Plots

fgf.glia.sub<-readRDS(here("data/glia/glia_seur_filtered.RDS"))

Start Plotting

tsne_embed<-data.frame(Embeddings(fgf.glia.sub, reduction = "umap"))
fgf.glia.sub$group<-paste0(fgf.glia.sub$trt, "_", fgf.glia.sub$day)
tsne_embed$group<-fgf.glia.sub$group
tsne_embed$celltype<-Idents(fgf.glia.sub)
tsne_embed<-tsne_embed[sample(nrow(tsne_embed)),]

label.df <- data.frame(cluster=levels(tsne_embed$celltype),label=levels(tsne_embed$celltype))
label.df_2 <- tsne_embed %>% 
  dplyr::group_by(celltype) %>% 
  dplyr::summarize(x = median(UMAP_1), y = median(UMAP_2))

p1<-ggplot(tsne_embed, aes(x=UMAP_1, y=UMAP_2, colour=celltype)) + 
  geom_point(alpha=0.75, size=2)  + 
  geom_label(data = label.df_2, aes(label = celltype, x=x, y=y), size=3, fontface="bold", inherit.aes = F, nudge_x = 1)  +
  theme_pubr() + theme(legend.position = "none") + ggsci::scale_color_igv()
p2<-ggplot(tsne_embed, aes(x=UMAP_1, y=UMAP_2, colour=group)) + 
  geom_point(alpha=.75, size=2) + 
  ggsci::scale_color_igv() + 
  theme_pubr(legend = "none")

Get colors for matching

g <- ggplot_build(p1)
cols<-data.frame(colours = as.character(unique(g$data[[1]]$colour)), 
             label = as.character(unique(g$plot$data[, g$plot$labels$colour])))
colvec<-as.character(cols$colours)
names(colvec)<-as.character(cols$label)

Generate Pseudo Counts

fgf.glia.sub<-ScaleData(fgf.glia.sub, verbose=F)
split_mats<-splitbysamp(fgf.glia.sub, split_by="sample")
names(split_mats)<-unique(Idents(fgf.glia.sub))
pb<-replicate(100, gen_pseudo_counts(split_mats, ncells=10)) 
names(pb)<-paste0(rep(names(split_mats)),rep(1:100, each=length(names(split_mats))))

Generate DESeq2 Objects

res<-rundeseq(pb)

Identify most responsive cell types

degenes<-lapply(res, function(x) {
  tryCatch({
    y<-x[[2]]
    y<-na.omit(y)
    data.frame(y)%>%filter(padj<0.1)%>%nrow()}, 
    error=function(err) {NA})
})

boxplot<-lapply(unique(Idents(fgf.glia.sub)), function(x) {
  y<-paste0("^",x)
  z<-unlist(degenes[grep(y, names(degenes))])
})


names(boxplot)<-unique(Idents(fgf.glia.sub))
genenum<-melt(boxplot)
colnames(genenum)<-c("number","CellType")
genenum <- write_csv(genenum, path = here("output/glia/glia_resampling_output.csv"))
deplot_re <- ggplot(genenum, aes(x=reorder(CellType, -number), y=number, fill=CellType)) + 
  geom_boxplot(outlier.shape = NA, notch = T, alpha=1) + scale_fill_manual(values = colvec) + theme_pubr() +
  theme(axis.text.x = element_text(angle=45, hjust=1), legend.position = "none") + 
  ylab("Differentially Expressed\n Genes") + xlab(NULL) 
deplot_re

Generate Pseudo Counts

split_mats<-lapply(unique(Idents(fgf.glia.sub)), function(x){
  sub<-subset(fgf.glia.sub, idents=x)
  DefaultAssay(sub)<-"SCT"
  list_sub<-SplitObject(sub, split.by="sample")
  return(list_sub)
})
names(split_mats)<-unique(Idents(fgf.glia.sub))

pseudo_counts<-lapply(split_mats, function(x){
  lapply(x, function(y) {
    DefaultAssay(y) <- "SCT"
    mat<-GetAssayData(y, slot="counts")
    counts <- Matrix::rowSums(mat)
    }) %>% do.call(rbind, .) %>% t() %>% as.data.frame()
})

names(pseudo_counts)<-names(split_mats)

Generate DESeq2 Objects

dds_list<-lapply(pseudo_counts, function(x){
  tryCatch({
      trt<-ifelse(grepl("FGF", colnames(x)), yes="F", no="P")
      number<-sapply(strsplit(colnames(x),"_"),"[",1)
      day<-ifelse(as.numeric(as.character(number))>10, yes="5", no="1")
      meta<-data.frame(trt=trt, day=factor(day))
      dds <- DESeqDataSetFromMatrix(countData = x,
                                    colData = meta,
                                    design = ~ 0 + trt)
      dds$group<-factor(paste0(dds$trt, "_", dds$day))
      design(dds) <- ~ 0 + group
      keep <- rowSums(counts(dds) >= 5) > 5
      dds <- dds[keep,]
      dds<-DESeq(dds)
      res_5<-results(dds, contrast = c("group","F_5","P_5"))
      res_1<-results(dds, contrast = c("group","F_1","P_1"))
      f_5_1<-results(dds, contrast = c("group","F_5","F_1"))
      p_5_1<-results(dds, contrast = c("group","P_5","P_1"))
      return(list(dds, res_1, res_5,f_5_1, p_5_1))
    }, error=function(err) {print(err)})
})

Volcano Plot of DE genes

volc_list<-lapply(dds_list, function(x) {
  x[[2]] %>% na.omit() %>% data.frame() %>% add_rownames("gene") %>% 
    mutate(siglog=ifelse(padj<0.05&abs(log2FoldChange)>1, yes=T, no=F)) %>% 
    mutate(onlysig=ifelse(padj<0.05&abs(log2FoldChange)<1, yes=T, no=F)) %>% 
    mutate(onlylog=ifelse(padj>0.05&abs(log2FoldChange)>1, yes=T, no=F)) %>% 
    mutate(col=ifelse(siglog==T, yes="1", no = 
                      ifelse(onlysig==T, yes="2", no = 
                               ifelse(onlylog==T, yes="3", no="4")))) %>% 
    arrange(padj) %>% mutate(label=ifelse(min_rank(padj) < 15, gene, "")) %>% 
    dplyr::select(gene, log2FoldChange, padj, col, label)
})
Warning: Deprecated, use tibble::rownames_to_column() instead.

Warning: Deprecated, use tibble::rownames_to_column() instead.

Warning: Deprecated, use tibble::rownames_to_column() instead.

Warning: Deprecated, use tibble::rownames_to_column() instead.

Warning: Deprecated, use tibble::rownames_to_column() instead.

Warning: Deprecated, use tibble::rownames_to_column() instead.

Warning: Deprecated, use tibble::rownames_to_column() instead.

Warning: Deprecated, use tibble::rownames_to_column() instead.
mapply(x=volc_list, y = names(volc_list), function(x,y) {
  write_csv(x, path = here(sprintf("output/glia/%s_glia_pseudobulk_dge.csv", y)))
})
               Astro          Olig           Micro          COP           
gene           Character,8681 Character,9346 Character,6068 Character,2820
log2FoldChange Numeric,8681   Numeric,9346   Numeric,6068   Numeric,2820  
padj           Numeric,8681   Numeric,9346   Numeric,6068   Numeric,2820  
col            Character,8681 Character,9346 Character,6068 Character,2820
label          Character,8681 Character,9346 Character,6068 Character,2820
               Tany           VLMC          Endo          Epend         
gene           Character,3731 Character,732 Character,956 Character,1478
log2FoldChange Numeric,3731   Numeric,732   Numeric,956   Numeric,1478  
padj           Numeric,3731   Numeric,732   Numeric,956   Numeric,1478  
col            Character,3731 Character,732 Character,956 Character,1478
label          Character,3731 Character,732 Character,956 Character,1478
plotlist<-mapply(x=volc_list[c("Astro","Tany","Epend", "VLMC")], y= c("Astro","Tany","Epend", "VLMC"), function(x,y){
    ggplot(x, aes(y=(-log10(padj)), x=log2FoldChange, colour=factor(col), label=label)) + 
    xlab(expression(Log[2]*~Fold*~Change)) + ylab(expression(-Log[10]*~pvalue)) + 
    geom_point(size=3, alpha=0.75) + geom_hline(yintercept = -log10(0.05), linetype="dashed") + 
    geom_vline(xintercept = c(-1,1), linetype="dashed") + geom_text_repel(colour="black") + theme_pubr() +
    theme(legend.position = "none", title = element_text(vjust=0.5)) + 
    scale_colour_manual(values = wes_palette("Royal1", 3, type="discrete")[c(2,1,3)]) + ggtitle(y)}, SIMPLIFY = FALSE)
devolc_plot <- plot_grid(plotlist=plotlist[c(1,2)], ncol=2)
devolc_plot

Overlap

res_glia_1<-lapply(dds_list, function(x) {
  data.frame(x[[2]]) %>% add_rownames("gene") %>% na.omit(x) %>% 
    filter(padj<0.05) %>% arrange(padj) %>% select(gene) -> x
})
Warning: Deprecated, use tibble::rownames_to_column() instead.

Warning: Deprecated, use tibble::rownames_to_column() instead.

Warning: Deprecated, use tibble::rownames_to_column() instead.

Warning: Deprecated, use tibble::rownames_to_column() instead.

Warning: Deprecated, use tibble::rownames_to_column() instead.

Warning: Deprecated, use tibble::rownames_to_column() instead.

Warning: Deprecated, use tibble::rownames_to_column() instead.

Warning: Deprecated, use tibble::rownames_to_column() instead.
resglia<-bind_rows(res_glia_1, .id="id")
resglia %>%
  dplyr::group_by(gene) %>%
  dplyr::summarize(Celltype = list(id)) -> resglia

upset <- ggplot(resglia, aes(x=Celltype)) +
    geom_bar(fill=c(rep("black",3),"red","red","red", rep("black",4))) + theme_pubr() +
    scale_x_upset(n_intersections = 10)
upset
Warning: Removed 13 rows containing non-finite values (stat_count).

top <- plot_grid(p1, deplot_re, labels=c("A","B"), scale=0.9)
bot <- plot_grid(devolc_plot, upset, axis="t", align="h", rel_widths = c(2,1), labels=c("C","D"))
Warning: Removed 13 rows containing non-finite values (stat_count).
fig <- plot_grid(top, bot, ncol=1, align="hv", axis="tblr", rel_heights = c(1,1.25,2.5))
fig

Correlation

library(ggcorrplot)
ranks<-lapply(dds_list, function(x) {
  x<-data.frame(x[[2]])
  x<-na.omit(x)
  y <- (-log10(x$pvalue))*(x$log2FoldChange)
  z <- rownames(x)
  df<-data.frame(order=y,gene=z)
  df<-df[order(-df$order),]
})

corframe<-Reduce(function(x, y) merge(x, y, all=T, by=c("gene")), ranks)
Warning in merge.data.frame(x, y, all = T, by = c("gene")): column names
'order.x', 'order.y' are duplicated in the result

Warning in merge.data.frame(x, y, all = T, by = c("gene")): column names
'order.x', 'order.y' are duplicated in the result
Warning in merge.data.frame(x, y, all = T, by = c("gene")): column names
'order.x', 'order.y', 'order.x', 'order.y' are duplicated in the result

Warning in merge.data.frame(x, y, all = T, by = c("gene")): column names
'order.x', 'order.y', 'order.x', 'order.y' are duplicated in the result
Warning in merge.data.frame(x, y, all = T, by = c("gene")): column names
'order.x', 'order.y', 'order.x', 'order.y', 'order.x', 'order.y' are
duplicated in the result
colnames(corframe)<-c("gene",names(ranks))
corframe<-corframe[,-1]
dim(corframe[complete.cases(corframe),])
[1] 363   8
plotcor <- cor(corframe, method = "spearman", use="complete.obs")
ggcorrplot(plotcor, hc.order = T, type="lower") + 
  ggsci::scale_fill_gsea(limit = c(0,1))


sessionInfo()
R version 3.5.3 (2019-03-11)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Storage

Matrix products: default
BLAS/LAPACK: /usr/lib64/libopenblas-r0.3.3.so

locale:
 [1] LC_CTYPE=en_DK.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_DK.UTF-8        LC_COLLATE=en_DK.UTF-8    
 [5] LC_MONETARY=en_DK.UTF-8    LC_MESSAGES=en_DK.UTF-8   
 [7] LC_PAPER=en_DK.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_DK.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] parallel  stats4    stats     graphics  grDevices utils     datasets 
[8] methods   base     

other attached packages:
 [1] gProfileR_0.6.7             ggcorrplot_0.1.3           
 [3] ggupset_0.1.0.9000          wesanderson_0.3.6.9000     
 [5] here_0.1                    ggpubr_0.2.1               
 [7] magrittr_1.5                reshape2_1.4.3             
 [9] ggrepel_0.8.1               forcats_0.4.0              
[11] stringr_1.4.0               dplyr_0.8.3                
[13] purrr_0.3.2                 readr_1.3.1.9000           
[15] tidyr_0.8.3                 tibble_2.1.3               
[17] ggplot2_3.2.1               tidyverse_1.2.1            
[19] cowplot_1.0.0               future.apply_1.3.0         
[21] future_1.14.0               DESeq2_1.22.2              
[23] SummarizedExperiment_1.12.0 DelayedArray_0.8.0         
[25] BiocParallel_1.16.6         matrixStats_0.54.0         
[27] Biobase_2.42.0              GenomicRanges_1.34.0       
[29] GenomeInfoDb_1.18.2         IRanges_2.16.0             
[31] S4Vectors_0.20.1            BiocGenerics_0.28.0        
[33] Seurat_3.0.3.9036          

loaded via a namespace (and not attached):
  [1] reticulate_1.13        R.utils_2.9.0          tidyselect_0.2.5      
  [4] RSQLite_2.1.1          AnnotationDbi_1.44.0   htmlwidgets_1.3       
  [7] grid_3.5.3             Rtsne_0.15             munsell_0.5.0         
 [10] codetools_0.2-16       ica_1.0-2              withr_2.1.2           
 [13] colorspace_1.4-1       highr_0.8              knitr_1.23            
 [16] rstudioapi_0.10        ROCR_1.0-7             ggsignif_0.5.0        
 [19] gbRd_0.4-11            listenv_0.7.0          Rdpack_0.11-0         
 [22] labeling_0.3           git2r_0.25.2           GenomeInfoDbData_1.2.0
 [25] bit64_0.9-7            rprojroot_1.3-2        vctrs_0.2.0           
 [28] generics_0.0.2         xfun_0.8               R6_2.4.0              
 [31] rsvd_1.0.2             locfit_1.5-9.1         bitops_1.0-6          
 [34] assertthat_0.2.1       SDMTools_1.1-221.1     scales_1.0.0          
 [37] nnet_7.3-12            gtable_0.3.0           npsurv_0.4-0          
 [40] globals_0.12.4         workflowr_1.4.0        rlang_0.4.0           
 [43] zeallot_0.1.0          genefilter_1.64.0      splines_3.5.3         
 [46] lazyeval_0.2.2         acepack_1.4.1          broom_0.5.2           
 [49] checkmate_1.9.4        yaml_2.2.0             modelr_0.1.4          
 [52] backports_1.1.4        Hmisc_4.2-0            tools_3.5.3           
 [55] gplots_3.0.1.1         RColorBrewer_1.1-2     ggridges_0.5.1        
 [58] Rcpp_1.0.2             plyr_1.8.4             base64enc_0.1-3       
 [61] zlibbioc_1.28.0        RCurl_1.95-4.12        rpart_4.1-15          
 [64] pbapply_1.4-1          zoo_1.8-6              haven_2.1.0           
 [67] cluster_2.1.0          fs_1.3.1               data.table_1.12.2     
 [70] lmtest_0.9-37          RANN_2.6.1             fitdistrplus_1.0-14   
 [73] hms_0.5.0              lsei_1.2-0             evaluate_0.14         
 [76] xtable_1.8-4           XML_3.98-1.20          readxl_1.3.1          
 [79] gridExtra_2.3          compiler_3.5.3         KernSmooth_2.23-15    
 [82] crayon_1.3.4           R.oo_1.22.0            htmltools_0.3.6       
 [85] Formula_1.2-3          geneplotter_1.60.0     RcppParallel_4.4.3    
 [88] lubridate_1.7.4        DBI_1.0.0              MASS_7.3-51.4         
 [91] Matrix_1.2-17          cli_1.1.0              R.methodsS3_1.7.1     
 [94] gdata_2.18.0           metap_1.1              igraph_1.2.4.1        
 [97] pkgconfig_2.0.2        foreign_0.8-71         plotly_4.9.0          
[100] xml2_1.2.0             annotate_1.60.1        XVector_0.22.0        
[103] bibtex_0.4.2           rvest_0.3.4            digest_0.6.20         
[106] sctransform_0.2.0      RcppAnnoy_0.0.12       tsne_0.1-3            
[109] rmarkdown_1.13         cellranger_1.1.0       leiden_0.3.1          
[112] htmlTable_1.13.1       uwot_0.1.3             gtools_3.8.1          
[115] nlme_3.1-140           jsonlite_1.6           viridisLite_0.3.0     
[118] pillar_1.4.2           ggsci_2.9              lattice_0.20-38       
[121] httr_1.4.1             survival_2.44-1.1      glue_1.3.1            
[124] png_0.1-7              bit_1.1-14             stringi_1.4.3         
[127] blob_1.1.1             latticeExtra_0.6-28    caTools_1.17.1.2      
[130] memoise_1.1.0          irlba_2.3.3            ape_5.3