Skip to content

[WIP] Helper function to remove batch effects #280

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 10 commits into
base: v1.6rc
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions lib/lcdbwf/R/helpers.R
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ library(heatmaply)
library(readr)
library(stringr)
library(tibble)
library(limma)
library(purrr)
library(tidyr)

Expand Down Expand Up @@ -893,3 +894,36 @@ write.clusterprofiler.results <- function(res, cprof.folder, label){
return(list(orig=filename.orig, split=filename.split))
}


#' Remove batch effect
#'
#' based on the [removeBatchEffect](rdrr.io/bio/limma/src/R/removeBatchEffect.R) function from limma (Gordan Smyth et al.)
#' @param x Numeric matrix containing log-expression values for a series of samples
#' @param batches Vector of batch factors/vectors
#' @param covariates Matrix or vector of numeric covariates to be adjusted for
#' @param design Design matrix relating to treatment conditions to be preserved, usually the design matrix with all experimental factors other than the batch effects
#' @param ... Other arguments are passed to lmFit
removebatchEffect <-
function(x, batches=c(), covariates=NULL, design=matrix(1,ncol(x),1),...)
{
if(length(batches) == 0 & is.null(covariates)){
return(as.matrix(x))
}
batches_processed <- c()
if(length(batches) != 0){
for(batch in batches){
batch <- as.factor(batch)
contrasts(batch) <- contr.sum(levels(batch))
batch <- model.matrix(~batch)[,-1,drop=FALSE]
batches_processed <- rbind(batches_processed, batch)
}
}
if(!is.null(covariates)) {
covariates <- as.matrix(covariates)
}
X.batch <- cbind(batches_processed, covariates)
fit <- lmFit(x, cbind(design, X.batch),...)
beta <- fit$coefficients[,-(1:ncol(design)),drop=FALSE]
beta[is.na(beta)] <- 0
as.matrix(x) - beta %*% t(X.batch)
}
35 changes: 35 additions & 0 deletions workflows/rnaseq/downstream/helpers.Rmd
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ library(heatmaply)
library(readr)
library(stringr)
library(tibble)
library(limma)
library(purrr)
library(tidyr)

Expand Down Expand Up @@ -868,4 +869,38 @@ write.clusterprofiler.results <- function(res, cprof.folder, label){
write.table(res.split, file=filename.split, sep='\t', quote=FALSE, row.names=FALSE)
return(list(orig=filename.orig, split=filename.split))
}


#' Remove batch effect
#'
#' based on the [removeBatchEffect](rdrr.io/bio/limma/src/R/removeBatchEffect.R) function from limma (Gordan Smyth et al.)
#' @param x Numeric matrix containing log-expression values for a series of samples
#' @param batches Vector of batch factors/vectors
#' @param covariates Matrix or vector of numeric covariates to be adjusted for
#' @param design Design matrix relating to treatment conditions to be preserved, usually the design matrix with all experimental factors other than the batch effects
#' @param ... Other arguments are passed to lmFit
removebatchEffect <-
function(x, batches=c(), covariates=NULL, design=matrix(1,ncol(x),1),...)
{
if(length(batches) == 0 & is.null(covariates)){
return(as.matrix(x))
}
batches_processed <- c()
if(length(batches) != 0){
for(batch in batches){
batch <- as.factor(batch)
contrasts(batch) <- contr.sum(levels(batch))
batch <- model.matrix(~batch)[,-1,drop=FALSE]
batches_processed <- rbind(batches_processed, batch)
}
}
if(!is.null(covariates)) {
covariates <- as.matrix(covariates)
}
X.batch <- cbind(batches_processed, covariates)
fit <- lmFit(x, cbind(design, X.batch),...)
beta <- fit$coefficients[,-(1:ncol(design)),drop=FALSE]
beta[is.na(beta)] <- 0
as.matrix(x) - beta %*% t(X.batch)
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this would benefit from a small test -- we wouldn't need to mock up a bunch of RNA-seq data for this, we could just use a small matrix.

And maybe as a temporary test you could copy the function over to a real-world RNA-seq analysis and give it a shot there -- no need to wait for a merge for that.

```
46 changes: 46 additions & 0 deletions workflows/rnaseq/downstream/test_batch_effects.Rmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Test removebatchEffects function

1. Install `airway` package, which has counts data for an experiment described
at
http://bioconductor.org/packages/release/data/experiment/html/airway.html:

```{r}
if (!requireNamespace("BiocManager", quietly = TRUE))
install.packages("BiocManager")
BiocManager::install("airway")
```

2. Load data, show colData

```{r}
library(airway)
library(DESeq2)
data(airway)
knitr::kable(colData(airway))
```


3. dds object; run vst; plot PCA:

```{r}
dds <- DESeqDataSet(airway, design = ~ cell + dex)
rld <- vst(dds, blind=TRUE)
plotPCA(rld, 'cell')
```

4. Load helpers

```{r child='helpers.Rmd', include=FALSE}
rmarkdown::render('helpers.Rmd', run_pandoc=FALSE)
```


5. Attempted usage here...imagine we want to remove the effect of cell type:

```{r}
coldata <- colData(rld)
no.cell <- removebatchEffect(assay(rld), batches=list(coldata$cell), design=model.matrix(~dex, data=coldata))
rld.nocell <- rld
assay(rld.nocell) <- no.cell
plotPCA(rld.nocell, 'cell')
```