From 9c7bd8736389d8a5345e18112cc293391c8c6d7e Mon Sep 17 00:00:00 2001 From: Lorena Pantano Date: Tue, 16 Apr 2024 12:46:07 -0400 Subject: [PATCH] a new beginning --- .Rbuildignore | 5 + .github/.gitignore | 1 + .github/workflows/R-CMD-check.yaml | 50 +++ .gitignore | 4 + DESCRIPTION | 11 + LICENSE | 23 +- LICENSE.md | 21 ++ NAMESPACE | 1 + R/hello.R | 18 ++ README.Rmd | 54 ++++ README.md | 52 ++++ .../templates/rnaseq_qc/skeleton/params_de.R | 15 + .../templates/rnaseq_qc/skeleton/skeleton.Rmd | 294 ++++++++++++++++++ .../templates/rnaseq_qc/template.yaml | 3 + man/hello.Rd | 12 + 15 files changed, 543 insertions(+), 21 deletions(-) create mode 100644 .Rbuildignore create mode 100644 .github/.gitignore create mode 100644 .github/workflows/R-CMD-check.yaml create mode 100644 .gitignore create mode 100644 DESCRIPTION create mode 100644 LICENSE.md create mode 100644 NAMESPACE create mode 100644 R/hello.R create mode 100644 README.Rmd create mode 100644 README.md create mode 100644 inst/rmarkdown/templates/rnaseq_qc/skeleton/params_de.R create mode 100644 inst/rmarkdown/templates/rnaseq_qc/skeleton/skeleton.Rmd create mode 100644 inst/rmarkdown/templates/rnaseq_qc/template.yaml create mode 100644 man/hello.Rd diff --git a/.Rbuildignore b/.Rbuildignore new file mode 100644 index 0000000..72b9b07 --- /dev/null +++ b/.Rbuildignore @@ -0,0 +1,5 @@ +^.*\.Rproj$ +^\.Rproj\.user$ +^\.github$ +^README\.Rmd$ +^LICENSE\.md$ diff --git a/.github/.gitignore b/.github/.gitignore new file mode 100644 index 0000000..2d19fc7 --- /dev/null +++ b/.github/.gitignore @@ -0,0 +1 @@ +*.html diff --git a/.github/workflows/R-CMD-check.yaml b/.github/workflows/R-CMD-check.yaml new file mode 100644 index 0000000..8e9e284 --- /dev/null +++ b/.github/workflows/R-CMD-check.yaml @@ -0,0 +1,50 @@ +# Workflow derived from https://github.com/r-lib/actions/tree/v2/examples +# Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help +on: + push: + branches: [main, master] + pull_request: + branches: [main, master] + +name: R-CMD-check + +jobs: + R-CMD-check: + runs-on: ${{ matrix.config.os }} + + name: ${{ matrix.config.os }} (${{ matrix.config.r }}) + + strategy: + fail-fast: false + matrix: + config: + - {os: macos-latest, r: 'release'} + #- {os: windows-latest, r: 'release'} + - {os: ubuntu-latest, r: 'devel', http-user-agent: 'release'} + - {os: ubuntu-latest, r: 'release'} + #- {os: ubuntu-latest, r: 'oldrel-1'} + + env: + GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} + R_KEEP_PKG_SOURCE: yes + + steps: + - uses: actions/checkout@v4 + + - uses: r-lib/actions/setup-pandoc@v2 + + - uses: r-lib/actions/setup-r@v2 + with: + r-version: ${{ matrix.config.r }} + http-user-agent: ${{ matrix.config.http-user-agent }} + use-public-rspm: true + + - uses: r-lib/actions/setup-r-dependencies@v2 + with: + extra-packages: any::rcmdcheck + needs: check + + - uses: r-lib/actions/check-r-package@v2 + with: + upload-snapshots: true + build_args: 'c("--no-manual","--compact-vignettes=gs+qpdf")' diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5b6a065 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.Rproj.user +.Rhistory +.RData +.Ruserdata diff --git a/DESCRIPTION b/DESCRIPTION new file mode 100644 index 0000000..4370dd8 --- /dev/null +++ b/DESCRIPTION @@ -0,0 +1,11 @@ +Package: bcbioR +Type: Package +Title: Templates and functions to guide downstream analysis and data interpretation +Version: 0.1.0 +Authors@R: person("Pantano", "Lorena", , "lorena.pantano@gmail.com", + role = c("aut", "cre")) +Description: Collaborative code repository from the Harvard Chan Bioinformatics Core. +License: MIT + file LICENSE +LazyData: true +Encoding: UTF-8 +Roxygen: list(markdown = TRUE) diff --git a/LICENSE b/LICENSE index 3da0486..d7531ab 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,2 @@ -MIT License - -Copyright (c) 2024 Blue Collar Bioinformatics - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +YEAR: 2024 +COPYRIGHT HOLDER: bcbioR authors diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..00a96b7 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +# MIT License + +Copyright (c) 2024 bcbioR authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/NAMESPACE b/NAMESPACE new file mode 100644 index 0000000..d75f824 --- /dev/null +++ b/NAMESPACE @@ -0,0 +1 @@ +exportPattern("^[[:alpha:]]+") diff --git a/R/hello.R b/R/hello.R new file mode 100644 index 0000000..3d348f2 --- /dev/null +++ b/R/hello.R @@ -0,0 +1,18 @@ +# Hello, world! +# +# This is an example function named 'hello' +# which prints 'Hello, world!'. +# +# You can learn more about package authoring with RStudio at: +# +# http://r-pkgs.had.co.nz/ +# +# Some useful keyboard shortcuts for package authoring: +# +# Install Package: 'Cmd + Shift + B' +# Check Package: 'Cmd + Shift + E' +# Test Package: 'Cmd + Shift + T' + +hello <- function() { + print("Hello, world!") +} diff --git a/README.Rmd b/README.Rmd new file mode 100644 index 0000000..3919fdc --- /dev/null +++ b/README.Rmd @@ -0,0 +1,54 @@ +--- +output: github_document +--- + +```{r, include = FALSE} +knitr::opts_chunk$set( + collapse = TRUE, + comment = "#>", + fig.path = "man/figures/README-", + out.width = "100%" +) +``` + +# bcbioR + + + [![R-CMD-check](https://github.com/bcbio/bcbioR/actions/workflows/R-CMD-check.yaml/badge.svg)](https://github.com/bcbio/bcbioR/actions/workflows/R-CMD-check.yaml) + + +The goal of bcbioR is to ... + +## Installation + +You can install the development version of bcbioR from [GitHub](https://github.com/) with: + +``` r +# install.packages("devtools") +devtools::install_github("bcbio/bcbioR") +``` + +## Example + +This is a basic example which shows you how to solve a common problem: + +```{r example} +library(bcbioR) +## basic example code +``` + +What is special about using `README.Rmd` instead of just `README.md`? You can include R chunks like so: + +```{r cars} +summary(cars) +``` + +You'll still need to render `README.Rmd` regularly, to keep `README.md` up-to-date. `devtools::build_readme()` is handy for this. + +You can also embed plots, for example: + +```{r pressure, echo = FALSE} +plot(pressure) +``` + +In that case, don't forget to commit and push the resulting figure files, so they display on GitHub and CRAN. diff --git a/README.md b/README.md new file mode 100644 index 0000000..3a23104 --- /dev/null +++ b/README.md @@ -0,0 +1,52 @@ + +# bcbioR + + + +[![R-CMD-check](https://github.com/bcbio/bcbioR/actions/workflows/R-CMD-check.yaml/badge.svg)](https://github.com/bcbio/bcbioR/actions/workflows/R-CMD-check.yaml) + + +The goal of bcbioR is to … + +## Installation + +You can install the development version of bcbioR from +[GitHub](https://github.com/) with: + +``` r +# install.packages("devtools") +devtools::install_github("bcbio/bcbioR") +``` + +## Example + +This is a basic example which shows you how to solve a common problem: + +``` r +library(bcbioR) +## basic example code +``` + +What is special about using `README.Rmd` instead of just `README.md`? +You can include R chunks like so: + +``` r +summary(cars) +#> speed dist +#> Min. : 4.0 Min. : 2.00 +#> 1st Qu.:12.0 1st Qu.: 26.00 +#> Median :15.0 Median : 36.00 +#> Mean :15.4 Mean : 42.98 +#> 3rd Qu.:19.0 3rd Qu.: 56.00 +#> Max. :25.0 Max. :120.00 +``` + +You’ll still need to render `README.Rmd` regularly, to keep `README.md` +up-to-date. `devtools::build_readme()` is handy for this. + +You can also embed plots, for example: + + + +In that case, don’t forget to commit and push the resulting figure +files, so they display on GitHub and CRAN. diff --git a/inst/rmarkdown/templates/rnaseq_qc/skeleton/params_de.R b/inst/rmarkdown/templates/rnaseq_qc/skeleton/params_de.R new file mode 100644 index 0000000..591a8cc --- /dev/null +++ b/inst/rmarkdown/templates/rnaseq_qc/skeleton/params_de.R @@ -0,0 +1,15 @@ +# info params +project = "name_hbcXXXXX" +PI = 'person name' +experiment = 'short description' +aim = 'short description' +analyst = 'person in the core' + +# project params +root = "../" +date = "YYYYMMDD" +column = "treatment" +subset_column = 'cell' +metadata_fn = "../meta/samplesheet.csv" +counts_fn = '../data/tximport-counts.csv' +basedir <- 'reports' diff --git a/inst/rmarkdown/templates/rnaseq_qc/skeleton/skeleton.Rmd b/inst/rmarkdown/templates/rnaseq_qc/skeleton/skeleton.Rmd new file mode 100644 index 0000000..4185d70 --- /dev/null +++ b/inst/rmarkdown/templates/rnaseq_qc/skeleton/skeleton.Rmd @@ -0,0 +1,294 @@ +--- +title: "Differential Expression" +author: "Harvard Chan Bioinformatics Core" +date: "`r Sys.Date()`" +output: + html_document: + code_folding: hide + df_print: paged + highlights: pygments + number_sections: true + self_contained: true + theme: default + toc: true + toc_float: + collapsed: true + smooth_scroll: true +editor_options: + chunk_output_type: console +params: + numerator: foo + denominator: bar + subset_value: nah + params_file: params_de.R + +--- + +```{r echo = F} +source(params$params_file) +``` + +```{r, cache = FALSE, message = FALSE, warning=FALSE, echo=FALSE,} +library(rtracklayer) +library(DESeq2) +library(tidyverse) +library(stringr) +library(RUVSeq) +library(DEGreport) +library(ggpubr) +library(msigdbr) +library(fgsea) +library(org.Hs.eg.db) +library(knitr) + +ggplot2::theme_set(theme_light(base_size = 14)) +opts_chunk[["set"]]( + cache = F, + cache.lazy = FALSE, + dev = c("png", "pdf"), + error = TRUE, + highlight = TRUE, + message = FALSE, + prompt = FALSE, + tidy = FALSE, + warning = FALSE, + echo = F, + fig.height = 4) +``` + +```{r sanitize-datatable} +sanitize_datatable = function(df, ...) { + # remove dashes which cause wrapping + DT::datatable(df, ..., rownames=gsub("-", "_", rownames(df)), + colnames=gsub("-", "_", colnames(df))) +} +``` + +# Overview + +- Project: `r project` +- PI: `r PI` +- Analyst: `r analyst` +- Experiment: `r experiment` +- Aim: `r aim` +- Comparison: `r paste0(params$subset_value, ': ', params$numerator, ' vs. ', params$denominator)` + +```{r create-filenames} +filenames = str_interp("${params$subset_value}_${params$numerator}_vs_${params$denominator}") +contrasts = c(column,params$numerator,params$denominator) + +name_expression_fn=file.path(root, + basedir, + str_interp("${filenames}_expression.csv")) +name_deg_fn=file.path(root, + basedir, + str_interp("${filenames}_deg.csv")) +name_pathways_fn=file.path(root, + basedir, + str_interp("${filenames}_pathways.csv")) + +``` + +```{r read-counts-data} +coldata=read.csv(metadata_fn, row.names = 1) +stopifnot(column %in% names(coldata)) + +# use only some samples, by default use all +coldata <- coldata[coldata[[paste(subset_column)]] == params$subset_value, ] +coldata <- coldata[coldata[[paste(column)]] %in% c(params$numerator, params$denominator), ] +rownames(coldata) <- coldata$description +coldata[[column]] = relevel(as.factor(coldata[[column]]), params$denominator) + +counts <- read_csv(counts_fn) %>% column_to_rownames('gene') +counts <- counts[,colnames(counts) %in% coldata$description] + + +# if the names don't match in order or string check files names and coldata information +counts = counts[rownames(coldata)] +stopifnot(all(names(counts) == rownames(coldata))) + +# gtf_df <- as.data.frame(rtracklayer::import(GTF)) +# gtf_df$gene_id <- sub("\\..*","\\", gtf_df$gene_id) # remove the ensembl numbering +# +# rdata <- gtf_df %>% filter(type == 'gene', gene_id %in% rownames(counts)) %>% +# dplyr::select(gene_id, gene_name) +# rdata$gene_name[is.na(rdata$gene_name)] <- rdata$gene_id[is.na(rdata$gene_name)] + +rdata = AnnotationDbi::select(org.Hs.eg.db, rownames(counts), 'SYMBOL', 'ENSEMBL') %>% + dplyr::select(gene_id = ENSEMBL, gene_name = SYMBOL) + +``` + +# Remove Unwanted Variability + +When performing differential expression analysis, it is important to ensure that any detected differences are truly a result of the experimental comparison being made and not any additional variability in the data. + +```{r before-RUV} + +dds_before <- DESeqDataSetFromMatrix(counts, coldata, design = ~1) + +vsd_before <- vst(dds_before) + +degPCA(assay(vsd_before), colData(vsd_before), + condition = column) + ggtitle('Before RUV') + +``` + +```{r do-RUV} +design <- coldata[[column]] +names(design) <- coldata$name +diffs <- makeGroups(design) +dat <- assay(vsd_before) +ruvset <- RUVs(dat, cIdx=rownames(dat), k=1, diffs, isLog = T, round = F) +vars <- ruvset$W + +new_cdata <- cbind(coldata, vars) + +formula <- as.formula(paste0("~ ", + paste0( + colnames(new_cdata)[grepl("W", colnames(new_cdata))], + collapse = " + " + ), " + ", column) +) +``` + +```{r after-RUV} +## Check if sample name matches +stopifnot(all(names(counts) == rownames(new_cdata))) + +dds_after <- DESeqDataSetFromMatrix(counts, new_cdata, design = formula) +vsd_after<- vst(dds_after, blind=FALSE) +degPCA(ruvset$normalizedCounts, new_cdata, + condition = column) + ggtitle('After RUV') + +``` + + +# Differential Expression + +Because it is difficult to accurately detect and quantify the expression of lowly expressed genes, differences in their expression between treatment conditions can be unduly exaggerated. We correct for this so that gene LFC is not dependent overall on basal gene expression level. + +```{r DE} +de <- DESeq(dds_after) + +# resultsNames(de) # check the order is right +resLFC = results(de, contrast=contrasts) +resLFCS <- lfcShrink(de, coef=resultsNames(de)[ncol(vars)+2], type="apeglm") + +res <- as.data.frame(resLFCS) %>% + rownames_to_column('gene_id') %>% left_join(rdata, by = 'gene_id') %>% + relocate(gene_name) %>% rename(lfc = log2FoldChange) %>% + mutate(pi = abs(lfc) * -log10(padj)) %>% arrange(-pi) + +res_sig <- res %>% filter(padj < 0.05) %>% arrange(padj) + +res_mod <- res %>% mutate(lfc = replace(lfc, lfc < -5, -5)) %>% mutate(lfc = replace(lfc, lfc > 5, 5)) +show <- as.data.frame(res_mod[1:10, c("lfc", "padj", "gene_name")]) + +degMA(as.DEGSet(resLFC)) + ggtitle('Before LFC Shrinking') +``` + +```{r} +degMA(as.DEGSet(resLFCS), limit = 2) + ggtitle('After LFC Shrinking') + +``` + +This volcano plot shows the genes that are significantly up- and down-regulated as a result of the difference in treatment. +```{r} +degVolcano(res_mod[,c('lfc', 'padj')], plot_text = show) + +``` + +## Differentially Expressed Genes +```{r sig_genes_table} +res_sig %>% sanitize_datatable +``` + +# Pathway Enrichment + +From the set of differentially expressed genes and using publicly available information about gene sets involved in biological processes and functions, we can calculate which biological processes and functions are significantly perturbed as a result of the treatment. + +```{r} +universe=res %>% + filter(!is.na(padj)) %>% pull(gene_id) +mapping = AnnotationDbi::select(org.Hs.eg.db, universe, 'ENTREZID', 'ENSEMBL') + +ranks_df <- res %>% + filter(padj < 0.01, !is.na(padj)) %>% # only if enough DE genes + arrange((lfc)) %>% + left_join(mapping, by = c("gene_id"="ENSEMBL")) %>% + rename(entrez_id=ENTREZID) %>% + filter(!is.na(entrez_id) & !is.na(padj)) +ranks <- ranks_df$lfc +names(ranks) <- ranks_df$entrez_id + +all_in_life=list( + msigdbr(species = "human", category = "H") %>% mutate(gs_subcat="Hallmark"), + msigdbr(species = "human", category = "C2", subcategory = "CP:REACTOME"), + msigdbr(species = "human", category = "C2", subcategory = "CP:KEGG"), + msigdbr(species = "human", category = "C2", subcategory = "CP:PID"), + msigdbr(species = "human", category = "C5", subcategory = "GO:BP"), + msigdbr(species = "human", category = "C5", subcategory = "GO:MF"), + msigdbr(species = "human", category = "C5", subcategory = "HPO"), + msigdbr(species = "human", category = "C3", subcategory = "TFT:GTRD"), + msigdbr(species = "human", category = "C6") %>% mutate(gs_subcat="Oncogenic") +) + +ora_input = res %>% filter(!is.na(padj), padj<0.01, abs(lfc)>0.3) %>% pull(gene_id) +input_entrezid <- AnnotationDbi::select(org.Hs.eg.db, ora_input, 'ENSEMBL', columns = c('ENTREZID', 'SYMBOL')) + +total_deg=length(unique(ora_input))/length(unique(mapping$ENTREZID)) +pathways_ora_all = lapply(all_in_life, function(p){ + pathway = split(x = p$entrez_gene, f = p$gs_name) + db_name = paste(p$gs_cat[1], p$gs_subcat[1],sep=":") + respath <- fora(pathways = pathway, + genes = unique(input_entrezid$ENTREZID), + universe = unique(mapping$ENTREZID), + minSize = 15, + maxSize = 500) + coll_respath = collapsePathwaysORA(respath[order(pval)][padj < 0.1], + pathway, unique(input_entrezid$ENTREZID), unique(mapping$ENTREZID)) + as_tibble(respath[pathway %in% coll_respath$mainPathways]) %>% + mutate(database=db_name, NES=(overlap/size)/(total_deg)) +}) %>% bind_rows() %>% + mutate(analysis="ORA") + +ora_tb = pathways_ora_all %>% unnest(overlapGenes) %>% + group_by(pathway) %>% + left_join(mapping, by =c("overlapGenes"="ENTREZID")) %>% + dplyr::select(pathway, padj, NES, ENSEMBL, analysis, + database) + +pathways_long = ora_tb + +``` + + +```{r pathaways_table} +pathways_ora_all %>% sanitize_datatable() +``` + + +```{r write-files} +counts_norm=ruvset$normalizedCounts %>% as.data.frame() %>% + rownames_to_column("gene_id") +write_csv(counts_norm %>% + mutate(subset = params$subset_value, + comparison = str_interp("${params$numerator}_vs_${params$denominator}")), + name_expression_fn) +write_csv(res %>% + mutate(subset = params$subset_value, + comparison = str_interp("${params$numerator}_vs_${params$denominator}")), + name_deg_fn) +write_csv(pathways_long %>% + mutate(subset = params$subset_value, + comparison = str_interp("${params$numerator}_vs_${params$denominator}")), + name_pathways_fn) +``` +# R session + +List and version of tools used for the DE report generation. + +```{r} +sessionInfo() +``` diff --git a/inst/rmarkdown/templates/rnaseq_qc/template.yaml b/inst/rmarkdown/templates/rnaseq_qc/template.yaml new file mode 100644 index 0000000..db9e4aa --- /dev/null +++ b/inst/rmarkdown/templates/rnaseq_qc/template.yaml @@ -0,0 +1,3 @@ +name: bcbio RNAseq QC +description: Standard RNAseq QC after running bcbio +create_dir: true diff --git a/man/hello.Rd b/man/hello.Rd new file mode 100644 index 0000000..0fa7c4b --- /dev/null +++ b/man/hello.Rd @@ -0,0 +1,12 @@ +\name{hello} +\alias{hello} +\title{Hello, World!} +\usage{ +hello() +} +\description{ +Prints 'Hello, world!'. +} +\examples{ +hello() +}