1 Installation

Install the package SOMNiBUS from Bioconductor.

if (!requireNamespace("BiocManager", quietly=TRUE))
    install.packages("BiocManager")

BiocManager::install("SOMNiBUS")

2 Introduction

SOMNiBUS aims to analyze count-based methylation data on predefined genomic regions, such as those obtained by targeted sequencing, and thus to identify differentially methylated regions (DMRs) that are associated with phenotypes or traits surch as cell types.

Major advantages of SOMNiBUS

  • enable complex associations with multiple phenotypes / traits using a Generalized Additive Model approach
  • the modeling strategy incorporates count-based methylation error rate arguments (i.e., p0 or false positive rate and p1 or true positive rate)

For a more comprehensive introduction of the SOMNiBUS approach, please read our SOMNiBUS paper (Kaiqiong Zhao 2020).

2.1 Citation

If you use this package, please cite our SOMNiBUS paper (Kaiqiong Zhao 2020).

3 Application

3.1 Rheumatoid arthritis study

Throughout this vignette, we illustrate the SOMNiBUS approach with analysis of a targeted region from a rheumatoid arthritis (RA) study. See help(RAdat) for further details. In this example, the phenotype of major interest is the RA status (coded as RA) and the adjusting variable is the cell type status (coded as T_cell) which is binary because the experiment used cell-type-separated blood samples, and methylation profiles were characterized for both T-cells and Monocytes. We will refer to both RA and T_cell as covariates. We are going to use the package SOMNiBUS to investigate the methylation patterns in this region and study association with RA status and cell type.

library(SOMNiBUS)

4 Input data

Currently, we require a matrix-type input of the methylated reads (Meth_Counts) and the read depth (Total_Counts) for CpG sites of each sample. Inputs in another format, such as Bismark or a BSeq object from the bsseq package are now supported using the formatting functions formatFromBSseq(), formatFromBismark() and formatFromBSmooth() (more details below).

Before using the package, the input data matrix (or data frame) should be formatted such that:

  1. each row represents a CpG site
  2. the first 4 columns should contain the information of Meth_Counts (methylated counts), Total_Counts (read depths), Position (Genomic position for the CpG site) and ID (sample ID)
  3. the covariate(s), such as disease status or cell type composition are listed in column 5 and onwards.

An example of the input data:

data("RAdat")
head(RAdat)
#>   Meth_Counts Total_Counts  Position ID T_cell RA
#> 1           0            8 102711629  1      0  1
#> 2           0            2 102711630  1      0  1
#> 3           0           12 102711702  1      0  1
#> 4           0            4 102711703  1      0  1
#> 5           0           15 102711747  1      0  1
#> 6           0            6 102711748  1      0  1

We implemented 3 functions dedicated to the conversion of outputs generated by standard whole-genome shotgun bisulfite sequencing (WGBS) tools such as BSseq R package (Hansen, Langmead, and Irizarry 2012), Bismark (Krueger, and Andrews 2011) and BSmooth (Hansen, Langmead, and Irizarry 2012) alignment suites.

4.1 formatFromBSseq

formatFromBSseq <- function(bsseq_dat, verbose = TRUE)

The function formatFromBSseq reads and converts a BSseq object (bsseq_dat) into a list of data.frames (one per chromosome) to a format compatible with runSOMNiBUS and binomRegMethModel. Each data.frame contains rows as individual CpGs appearing in all samples. The first 4 columns contain the information of Meth_Counts (methylated counts), Total_Counts (read depths), Position (Genomic position for the CpG site) and ID (sample ID).

The additional information (such as disease status, sex, age) extracted from the BSseq object are listed in column 5 and onwards and will be considered as covariate information by SOMNiBUS algorithms.

4.2 formatFromBSseq and formatFromBSmooth

The functions formatFromBismark and formatFromBSmooth utilize pre-existing methods implemented in the bsseq R package, read.bismark and read.bsmooth to convert, respectively, Bismark and BSmooth outputs into BSseq objects.

Once this conversion is applied, we call formatFromBSseq to generate the final output (described above).

formatFromBismark <- function(..., verbose = TRUE)

formatFromBSmooth <- function(..., verbose = TRUE)

... refers to the parameters from bsseq::read.bismark() or bsseq::read.bsmooth() functions. Use ?bsseq::read.bismark() or ?bsseq::read.bsmooth() for more information.

4.3 Filtering CpGs and samples

To better use the information in the methylation dataset, on one hand, SOMNiBUS uses a smoothing technique (regression splines) to borrow information from the nearby CpG sites; on the other hand, our approach uses regression-based modelling to take advantage of information contained across samples. Therefore, this algorithm does not require filtering out the CpG sites that have methylation levels measured only in a small part of the samples, or the samples that have overall poor read-depths and many missing values. Our analysis of differentially methylated regions (DMRs) requires filtering only on the following two conditions:

  • individual CpGs that have zero reads in a particular sample (no observation available)
  • samples that have missing values in any of the covariates of interest (i.e missing values for T_cell or RA in the data set RAdat)
RAdat.f <- na.omit(RAdat[RAdat$Total_Counts != 0, ])

4.4 Adjusting for covariates and adding interactions

  • we currently only accept numeric input for the covariates used to fit the model. we recommend that first you transform your categorical variables into appropriate dummy variables
  • interaction terms can be added in the analysis model. To do that, the program requires that users add another column of covariate values into the input data set calculated as the product of two existing covariates whose interaction is of interest.

5 Analysis

The smooth covariate estimation and the region-wise test steps are wrapped into a function binomRegMethModel. See help(binomRegMethModel) for more details. We can use the following code to run the analysis with both covariates T_cell and RA.

If there is a single region to analyze, we can directly call the function binomRegMethModel. We can use the following code to run the analysis with both covariates T_cell and RA.

out <- binomRegMethModel(data = RAdat.f, n.k = rep(5, 3), p0 = 0.003, 
                         p1 = 0.9, Quasi = FALSE, RanEff = FALSE,
                         verbose = FALSE)

Or, we can use the argument covs to specify that we only want the covariate T_cell in the model.

out.ctype <- binomRegMethModel(data = RAdat.f, n.k = rep(5, 2), p0 = 0.003,
                               p1 = 0.9, covs = "T_cell", verbose = FALSE)

If the analysis encompasses multiple regions, we use a wrapper function runSOMNiBUS (See help(runSOMNiBUS) for more details) which encapsulates the function binomRegMethModel. This function splits the methylation data into regions (according to different approaches) and, for each region, calls the function binomRegMethModel to fit a (dispersion-adjusted) binomial regression model to regional methylation data. It returns a list (one element by independent region) of results generated by the function binomRegMethModel. Each result reports the estimated smooth covariate effects and regional p-values for the test of DMRs. Over or under dispersion across loci is accounted for in the model by the combination of a multiplicative dispersion parameter (or scale parameter) and a sample-specific random effect.

The four main approaches are:

  • region which splits methylation data into regions based on the spacing of CpGs. See help(splitDataByRegion) for more details.
  • density which splits methylation data into regions based on the density of CpGs. See help(splitDataByDensity) for more details.
  • gene which splits methylation data into regions based on the genomic annotations. See help(splitDataByGene) for more details.
  • chromatin which splits methylation data into regions based on the chromatin states. See help(splitDataByChromatin) for more details.

Two generic approaches have also been implemented to enable users to use their own annotations for partitioning purposes:

  • bed which splits methylation data into regions based on the genomic annotations provided under the form of a 1-based BED file (the bases are numerated starting at 1). See help(splitDataByBed) for more details.
  • granges which splits methylation data into regions based on the genomic annotations provided under the form of a GenomicRanges object. See help(splitDataByGRanges) for more details.

Specifically, the granges approach is used internally to align and partition annotation data coming from bed, gene and chromatin approaches.

Each partitioning function requires a data frame (dat) with rows as individual CpGs appearing in all the samples. The first 4 columns contain the information of Meth_Counts (methylated counts), Total_Counts (read depths), Position (Genomic position for the CpG site) and ID (sample ID). The covariate information, such as disease status or cell type composition, are listed in column 5 and onwards. These partitioning functions return a named list of data.frame containing the data of each independent region. By default, the partitioning approach (region) splits the methylation data into regions based on the spacing between CpGs.

The following command line enables to split my the input data based on the spacing between CpG (CpG islands) and analyze each region:

outs <- runSOMNiBUS(dat = RAdat.f,
                    split = list(approach = "region", gap = 100),
                    n.k = rep(10,3), p0 = 0.003, p1 = 0.9, 
                    min.cpgs = 10, max.cpgs = 2000, verbose = TRUE)
#> [2024-05-01 19:32:30][INFO] Running runSOMNiBUS(): Processing methylation data.
#> [2024-05-01 19:32:30][INFO] Running splitDataByRegion(): Partitioning the regions based on the spacing of CpGs
#> [2024-05-01 19:32:30][INFO] Running splitDataByRegion(): Dropped region [102712831-102712832] containing 2 measurement points: below minimal region size accepted for analysis (10).
#> [2024-05-01 19:32:30][INFO] Finished splitDataByRegion(): Process completed in 0.047 secs
#> [2024-05-01 19:32:30][INFO] Input partitioned into 1 independent region(s)
#> [2024-05-01 19:32:30][INFO] Starting analysis for region_102711629_102712708 (119 unique CpGs)
#> [2024-05-01 19:32:30][INFO] Running binomRegMethModelInit(): Initialize data for binomRegMethModel
#> [2024-05-01 19:32:30][INFO] Running binomRegMethModelChecks(): Check inputs consistency
#> [2024-05-01 19:32:30][INFO] Running binomRegMethModelChecks(): We recommend basis dimentions n.k approximately equal to the number of unique CpGs in the region divided by 20
#> [2024-05-01 19:32:30][INFO] Finished binomRegMethModelInit(): Process completed in 0.0037 secs
#> [2024-05-01 19:32:30][INFO] Running fitGam(): Fit gam for the initial value
#> [2024-05-01 19:32:40][INFO] Finished fitGam(): Process completed in 9.4 secs
#> [2024-05-01 19:32:40][INFO] Running phiFletcher(): Calculating the Fletcher-based dispersion estimate from the final gam output
#> [2024-05-01 19:32:40][INFO] Finished phiFletcher(): Process completed in 9e-04 secs
#> [2024-05-01 19:32:40][INFO] Running fitEM(): Running EM algorithm to obtain the estimate of alpha
#> [2024-05-01 19:32:40][INFO] Running binomRegMethModelUpdate(): One-step update inside the EM algorithm for fitting the functional parameters theta.0 and beta.
#> [2024-05-01 19:32:45][INFO] Finished binomRegMethModelUpdate(): Process completed in 4.8 secs
#> [2024-05-01 19:32:45][INFO] iteration 1
#> [2024-05-01 19:32:53][INFO] iteration 2
#> [2024-05-01 19:32:58][INFO] iteration 3
#> [2024-05-01 19:33:05][INFO] iteration 4
#> [2024-05-01 19:33:10][INFO] iteration 5
#> [2024-05-01 19:33:15][INFO] iteration 6
#> [2024-05-01 19:33:22][INFO] iteration 7
#> [2024-05-01 19:33:28][INFO] iteration 8
#> [2024-05-01 19:33:36][INFO] iteration 9
#> [2024-05-01 19:33:42][INFO] iteration 10
#> [2024-05-01 19:33:50][INFO] iteration 11
#> [2024-05-01 19:33:57][INFO] iteration 12
#> [2024-05-01 19:34:04][INFO] iteration 13
#> [2024-05-01 19:34:11][INFO] iteration 14
#> [2024-05-01 19:34:18][INFO] iteration 15
#> [2024-05-01 19:34:25][INFO] iteration 16
#> [2024-05-01 19:34:32][INFO] iteration 17
#> [2024-05-01 19:34:38][INFO] iteration 18
#> [2024-05-01 19:34:46][INFO] iteration 19
#> [2024-05-01 19:34:52][INFO] iteration 20
#> [2024-05-01 19:35:00][INFO] iteration 21
#> [2024-05-01 19:35:06][INFO] Finished fitEM(): Process completed in 2.4 mins
#> [2024-05-01 19:35:06][INFO] Running estimateBZ(): Get the basis matrix for beta0(t) and beta(t)
#> [2024-05-01 19:35:06][INFO] Finished estimateBZ(): Process completed in 0.0028 secs
#> [2024-05-01 19:35:06][INFO] Running estimateBeta(): Given a final GAM output, extract the estimates of beta(t) = BZ * alpha
#> [2024-05-01 19:35:06][INFO] Finished estimateBeta(): Process completed in 0.00059 secs
#> [2024-05-01 19:35:06][INFO] Running estimateVar(): Estimate the variance covariance matrix
#> [2024-05-01 19:35:06][INFO] Running hessianComp(): Compute the Hessian matrix for an EM estimate
#> [2024-05-01 19:35:08][INFO] Finished hessianComp(): Process completed in 1.8 secs
#> [2024-05-01 19:35:08][INFO] Finished estimateVar(): Process completed in 1.8 secs
#> [2024-05-01 19:35:08][INFO] Running estimateSE(): Estimate SE of beta(t) for each covariates
#> [2024-05-01 19:35:08][INFO] Finished estimateSE(): Process completed in 0.00068 secs
#> [2024-05-01 19:35:08][INFO] Running extractDesignMatrix(): Extract design matrix
#> [2024-05-01 19:35:08][INFO] Finished extractDesignMatrix(): Process completed in 0.00046 secs
#> [2024-05-01 19:35:08][INFO] Running binomRegMethModelSummary(): Extract the regional testing results from a GamObj
#> [2024-05-01 19:35:08][INFO] Running binomRegMethModelSummary(): Get the regional summary results for an individual covariate effect
#> [2024-05-01 19:35:08][INFO] Finished binomRegMethModelSummary(): Process completed in 0.0076 secs
#> [2024-05-01 19:35:08][INFO] Running binomRegMethModelSummary(): Extract the regional testing results from a GamObj
#> [2024-05-01 19:35:08][INFO] Running binomRegMethModelSummary(): Get the regional summary results for an individual covariate effect
#> [2024-05-01 19:35:08][INFO] Finished binomRegMethModelSummary(): Process completed in 0.0064 secs
#> [2024-05-01 19:35:08][INFO] Finished binomRegMethModel(): Process completed in 2.6 mins
#> [2024-05-01 19:35:08][INFO] Finished runSOMNiBUS(): Process completed in 2.6 mins

5.1 Error rates p0 and p1

In the example data set, we have cell type separated samples. The error rates for individual samples can be estimated by a E-M algorithm (Lakhal-Chaieb et al. 2017) using the package SmoothMSC. The error rate default values, \(p_0=0.003\) and \(p_1=0.9\), were estimated as the average incomplete (\(p_0\)) or over- conversion (\(1-p_1\)) of the metabisulfite. These two estimated values coincide roughly with the incomplete and over conversion rates related to bisulfite sequencing experiment reported in Prochenka et al. (2015). Both parameters, p0 and p1, correspond to the false positive rate and the true positive rate respectively, where 1-p1 being the false negative rate.

For experiments with samples from a tissue containing a mixture of cell types, the user could consider the following ways to specify the error rates p0 and 1-p1.

  • If users have conducted experiments for measuring error/conversion rates, such as adding spike-in sequences of DNA that are known in advance to be methylated or unmethylated into the bisulfite sequencing procedure, they can use the measured error rates for the input of p0 and p1
  • One can also use the error rates (incomplete and over conversion rates) that have been previous reported in the literature.
  • Another option is to use our default values.

5.2 Basis dimensions n.k:

Argument n.k in the binomRegMethModel is the dimension of the basis expansion for smooth covariate effects. The exact number n.k used for each functional parameter is not crucial, because it only sets an upper bound. We recommend choosing a basis dimension approximately equal to the number of unique CpGs in the region divided by 20. Please notice that, this parameter is computed automatically (overwriting the value provided by the user if any), when several regions are generated by the partitioning function within the wrapper function runSOMNiBUS.

as.integer(length(unique(RAdat.f$Position)) / 20)
#> [1] 6

6 Results

6.1 testing the null hypothesis

Under the null hypothesis, we are expecting no effects of the covariates over the region-wide methylation status.

out$reg.out
#>                EDF    Chi.sq       p-value
#> Intercept 3.999034 584.06810 2.366352e-125
#> T_cell    2.007277 999.31851 1.763330e-217
#> RA        3.903903  80.44909  2.116877e-16

6.2 Estimation of the smooth covariate effects

binomRegMethModelPlot(BEM.obj = out)
#> [2024-05-01 19:35:08][INFO] Running binomRegMethModelPlot(): Plot the smooth covariate effect
#> Warning in geom_line(): All aesthetics have length 1, but the data has 363 rows.
#> ℹ Please consider using `annotate()` or provide this layer with data containing
#>   a single row.
#> Warning in geom_line(aes(y = "Lower"), linetype = "dashed"): All aesthetics have length 1, but the data has 363 rows.
#> ℹ Please consider using `annotate()` or provide this layer with data containing
#>   a single row.
#> Warning in geom_line(aes(y = "Upper"), linetype = "dashed"): All aesthetics have length 1, but the data has 363 rows.
#> ℹ Please consider using `annotate()` or provide this layer with data containing
#>   a single row.
#> Warning in geom_rug(sides = "b", color = "black"): All aesthetics have length 1, but the data has 363 rows.
#> ℹ Please consider using `annotate()` or provide this layer with data containing
#>   a single row.
The estimates (solid lines) and 95% pointwise confidence intervals (dashed lines) of the intercept, the smooth effect of cell type and RA on methylation levels.

Figure 1: The estimates (solid lines) and 95% pointwise confidence intervals (dashed lines) of the intercept, the smooth effect of cell type and RA on methylation levels

We can also force the covariate effect plots to have the same vertical range, for all covariates, by specifying same.range = TRUE.

binomRegMethModelPlot(out, same.range = TRUE)
#> [2024-05-01 19:35:09][INFO] Running binomRegMethModelPlot(): Plot the smooth covariate effect
#> Warning in geom_line(): All aesthetics have length 1, but the data has 363 rows.
#> ℹ Please consider using `annotate()` or provide this layer with data containing
#>   a single row.
#> Warning in geom_line(aes(y = "Lower"), linetype = "dashed"): All aesthetics have length 1, but the data has 363 rows.
#> ℹ Please consider using `annotate()` or provide this layer with data containing
#>   a single row.
#> Warning in geom_line(aes(y = "Upper"), linetype = "dashed"): All aesthetics have length 1, but the data has 363 rows.
#> ℹ Please consider using `annotate()` or provide this layer with data containing
#>   a single row.
#> Warning in geom_rug(sides = "b", color = "black"): All aesthetics have length 1, but the data has 363 rows.
#> ℹ Please consider using `annotate()` or provide this layer with data containing
#>   a single row.
The estimates (solid lines) and 95% pointwise confidence intervals (dashed lines) of the intercept, the smooth effect of cell type and RA on methylation levels. (Same ranges of Y axis.)

Figure 2: The estimates (solid lines) and 95% pointwise confidence intervals (dashed lines) of the intercept, the smooth effect of cell type and RA on methylation levels
(Same ranges of Y axis.)

The user can select a subset of covariates of interest by indicating the name of those covariates with the covs arguments.

# creating plot 
binomRegMethModelPlot(BEM.obj = out, same.range = FALSE, verbose = FALSE,
                      covs = c("RA", "T_cell"))
#> Warning in geom_line(): All aesthetics have length 1, but the data has 242 rows.
#> ℹ Please consider using `annotate()` or provide this layer with data containing
#>   a single row.
#> Warning in geom_line(aes(y = "Lower"), linetype = "dashed"): All aesthetics have length 1, but the data has 242 rows.
#> ℹ Please consider using `annotate()` or provide this layer with data containing
#>   a single row.
#> Warning in geom_line(aes(y = "Upper"), linetype = "dashed"): All aesthetics have length 1, but the data has 242 rows.
#> ℹ Please consider using `annotate()` or provide this layer with data containing
#>   a single row.
#> Warning in geom_rug(sides = "b", color = "black"): All aesthetics have length 1, but the data has 242 rows.
#> ℹ Please consider using `annotate()` or provide this layer with data containing
#>   a single row.
The estimates (solid lines) and 95% pointwise confidence intervals (dashed lines) of the smooth effect of cell type and RA on methylation levels.

Figure 3: The estimates (solid lines) and 95% pointwise confidence intervals (dashed lines) of the smooth effect of cell type and RA on methylation levels

The mfrow parameter allows you to create a matrix of plots in one plotting space. It takes a vector of length two as an argument, corresponding to the number of rows and columns in the resulting plotting matrix.

# creating a 2x2 matrix 
binomRegMethModelPlot(BEM.obj = out, same.range = FALSE, verbose = FALSE,
                      mfrow = c(2,2))
#> Warning in geom_line(): All aesthetics have length 1, but the data has 363 rows.
#> ℹ Please consider using `annotate()` or provide this layer with data containing
#>   a single row.
#> Warning in geom_line(aes(y = "Lower"), linetype = "dashed"): All aesthetics have length 1, but the data has 363 rows.
#> ℹ Please consider using `annotate()` or provide this layer with data containing
#>   a single row.
#> Warning in geom_line(aes(y = "Upper"), linetype = "dashed"): All aesthetics have length 1, but the data has 363 rows.
#> ℹ Please consider using `annotate()` or provide this layer with data containing
#>   a single row.
#> Warning in geom_rug(sides = "b", color = "black"): All aesthetics have length 1, but the data has 363 rows.
#> ℹ Please consider using `annotate()` or provide this layer with data containing
#>   a single row.
The estimates (solid lines) and 95% pointwise confidence intervals (dashed lines) of the intercept, the smooth effect of cell type and RA on methylation levels.

Figure 4: The estimates (solid lines) and 95% pointwise confidence intervals (dashed lines) of the intercept, the smooth effect of cell type and RA on methylation levels


# creating a 3x1 matrix 
binomRegMethModelPlot(BEM.obj = out, same.range = FALSE, verbose = FALSE,
                      mfrow = c(3,1))
#> Warning in geom_line(): All aesthetics have length 1, but the data has 363 rows.
#> ℹ Please consider using `annotate()` or provide this layer with data containing
#>   a single row.
#> Warning in geom_line(aes(y = "Lower"), linetype = "dashed"): All aesthetics have length 1, but the data has 363 rows.
#> ℹ Please consider using `annotate()` or provide this layer with data containing
#>   a single row.
#> Warning in geom_line(aes(y = "Upper"), linetype = "dashed"): All aesthetics have length 1, but the data has 363 rows.
#> ℹ Please consider using `annotate()` or provide this layer with data containing
#>   a single row.
#> Warning in geom_rug(sides = "b", color = "black"): All aesthetics have length 1, but the data has 363 rows.
#> ℹ Please consider using `annotate()` or provide this layer with data containing
#>   a single row.
The estimates (solid lines) and 95% pointwise confidence intervals (dashed lines) of the intercept, the smooth effect of cell type and RA on methylation levels.

Figure 5: The estimates (solid lines) and 95% pointwise confidence intervals (dashed lines) of the intercept, the smooth effect of cell type and RA on methylation levels

6.3 Predicted methylation levels

First, construct a new data set for prediction. Make sure that the Position in the new data set is the same as the original input data in runSOMNiBUS (or binomRegMethModel).

# simulating new data
pos <- out$uni.pos
my.p <- length(pos)
newdata <- expand.grid(pos, c(0, 1), c(0, 1))
colnames(newdata) <- c("Position", "T_cell", "RA")

The predicted methylation levels can be calculated from function binomRegMethModelPred using both prediction types (link.scale and proportion). See help(binomRegMethModelPred) for more details.

# prediction of methylation levels for the new data (logit scale)
my.pred.log <- binomRegMethModelPred(out, newdata, type = "link.scale", 
                                 verbose = FALSE)

# prediction of methylation levels for the new data (proportion)
my.pred.prop <- binomRegMethModelPred(out, newdata, type = "proportion", 
                                  verbose = FALSE)

We can visualize the prediction results using the function binomRegMethPredPlot (see help(binomRegMethPredPlot) for more details). We defined some experimental design in order to identify the different expression patterns based on the different disease and cell type status. In the following example, we created 4 groups of samples:

  • controls (RA == 0) t-cells (T_cell == 1),

  • controls (RA == 0) monocytes (T_cell == 0),

  • cases (RA == 1) t-cells (T_cell == 1),

  • cases (RA == 1) monocytes (T_cell == 0).

And add the design to the input data and prediction results using the following code:

# creating the experimental design
newdata$group <- ""
newdata[(newdata$RA == 0 & newdata$T_cell == 0),]$group <- "CTRL MONO"
newdata[(newdata$RA == 0 & newdata$T_cell == 1),]$group <- "CTRL TCELL"
newdata[(newdata$RA == 1 & newdata$T_cell == 0),]$group <- "RA MONO"
newdata[(newdata$RA == 1 & newdata$T_cell == 1),]$group <- "RA TCELL"

# merge input data and prediction results
pred <- cbind(newdata, Logit = my.pred.log, Prop = my.pred.prop)
head(pred)
#>    Position T_cell RA     group     Logit         Prop
#> 1 102711629      0  0 CTRL MONO -6.062564 0.0023230139
#> 2 102711630      0  0 CTRL MONO -6.083959 0.0022739534
#> 3 102711702      0  0 CTRL MONO -7.585820 0.0005073406
#> 4 102711703      0  0 CTRL MONO -7.605609 0.0004974049
#> 5 102711747      0  0 CTRL MONO -8.424272 0.0002194269
#> 6 102711748      0  0 CTRL MONO -8.441490 0.0002156818

Once the data are ready, we create a style describing the way each group should be displayed in the plot. If style = NULL, the default color and line type are picked.

# creating the custom style for each experimental group
style <- list(
  "CTRL MONO" = list(color = "blue", type = "solid"),
  "CTRL TCELL" = list(color = "green", type = "solid"),
  "RA MONO" = list(color = "red", type = "solid"),
  "RA TCELL" = list(color = "black", type = "solid")
) 

The following code enables to visualize the two types of prediction results.

# creating plot (logit scale)
binomRegMethPredPlot(pred = pred, pred.type = "link.scale", 
                     pred.col = "Logit", group.col = "group", 
                     title = "Logit scale",
                     style = style, verbose = TRUE)
#> [2024-05-01 19:35:12][INFO] Running binomRegMethPredPlot(): Plot the predicted methylation levels
#> Warning in geom_line(mapping = aes(y = pred.col, group = group.col, color = group.col, : All aesthetics have length 1, but the data has 484 rows.
#> ℹ Please consider using `annotate()` or provide this layer with data containing
#>   a single row.
#> Warning in geom_rug(sides = "b", color = "black"): All aesthetics have length 1, but the data has 484 rows.
#> ℹ Please consider using `annotate()` or provide this layer with data containing
#>   a single row.
#> Warning: No shared levels found between `names(values)` of the manual scale and the
#> data's colour values.
#> Warning: No shared levels found between `names(values)` of the manual scale and the
#> data's linetype values.
#> Warning: No shared levels found between `names(values)` of the manual scale and the
#> data's colour values.
#> Warning: No shared levels found between `names(values)` of the manual scale and the
#> data's linetype values.
The predicted methylation levels in the logit scale for the 4 groups of samples with different disease and cell type status.

Figure 6: The predicted methylation levels in the logit scale for the 4 groups of samples with different disease and cell type status

# creating plot (proportion)
binomRegMethPredPlot(pred = pred, pred.type = "proportion",
                     pred.col = "Prop", group.col = "group",
                     title = "Proportion scale",
                     style = style, verbose = FALSE)
#> Warning in geom_line(mapping = aes(y = pred.col, group = group.col, color = group.col, : All aesthetics have length 1, but the data has 484 rows.
#> ℹ Please consider using `annotate()` or provide this layer with data containing
#>   a single row.
#> Warning in geom_rug(sides = "b", color = "black"): All aesthetics have length 1, but the data has 484 rows.
#> ℹ Please consider using `annotate()` or provide this layer with data containing
#>   a single row.
#> Warning: No shared levels found between `names(values)` of the manual scale and the
#> data's colour values.
#> Warning: No shared levels found between `names(values)` of the manual scale and the
#> data's linetype values.
#> Warning: No shared levels found between `names(values)` of the manual scale and the
#> data's colour values.
#> Warning: No shared levels found between `names(values)` of the manual scale and the
#> data's linetype values.
The predicted methylation levels in the proportion scale for the 4 groups of samples with different disease and cell type status.

Figure 7: The predicted methylation levels in the proportion scale for the 4 groups of samples with different disease and cell type status

By default, no experimental design is required (group.col = NULL). In this case, the prediction results are displayed as a scatter plot.

binomRegMethPredPlot(pred = pred, pred.type = "link.scale", pred.col = "Logit", 
                     group.col = NULL, title = "Logit scale", verbose = FALSE)
#> Warning in geom_point(mapping = aes(y = pred.col)): All aesthetics have length 1, but the data has 484 rows.
#> ℹ Please consider using `annotate()` or provide this layer with data containing
#>   a single row.
#> Warning in geom_rug(sides = "b", color = "black"): All aesthetics have length 1, but the data has 484 rows.
#> ℹ Please consider using `annotate()` or provide this layer with data containing
#>   a single row.
The predicted methylation levels in the logit scale without any experimental design.

Figure 8: The predicted methylation levels in the logit scale without any experimental design

By putting the group value to NA or "" (empty character), we can specifically exclude some experimental groups from the plot. In the following example, we excluded monocytes.

# exclusion of the MONO cells (not T_cell)
pred[(pred$RA == 0 & pred$T_cell == 0),]$group <- NA
pred[(pred$RA == 1 & pred$T_cell == 0),]$group <- ""

# creating plot (logit scale)
binomRegMethPredPlot(pred = pred, pred.type = "link.scale", 
                     pred.col = "Logit", group.col = "group", 
                     title = "Logit scale",
                     style = style, verbose = FALSE)
#> Warning in geom_line(mapping = aes(y = pred.col, group = group.col, color = group.col, : All aesthetics have length 1, but the data has 242 rows.
#> ℹ Please consider using `annotate()` or provide this layer with data containing
#>   a single row.
#> Warning in geom_rug(sides = "b", color = "black"): All aesthetics have length 1, but the data has 242 rows.
#> ℹ Please consider using `annotate()` or provide this layer with data containing
#>   a single row.
#> Warning: No shared levels found between `names(values)` of the manual scale and the
#> data's colour values.
#> Warning: No shared levels found between `names(values)` of the manual scale and the
#> data's linetype values.
#> Warning: No shared levels found between `names(values)` of the manual scale and the
#> data's colour values.
#> Warning: No shared levels found between `names(values)` of the manual scale and the
#> data's linetype values.
The predicted methylation levels in the logit scale for the T-cell samples.

Figure 9: The predicted methylation levels in the logit scale for the T-cell samples

Session info

Here is the output of sessionInfo() on the system on which this document was compiled running pandoc 2.7.3:

#> R version 4.4.0 beta (2024-04-15 r86425)
#> Platform: x86_64-pc-linux-gnu
#> Running under: Ubuntu 22.04.4 LTS
#> 
#> Matrix products: default
#> BLAS:   /home/biocbuild/bbs-3.19-bioc/R/lib/libRblas.so 
#> LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.10.0
#> 
#> locale:
#>  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
#>  [3] LC_TIME=en_GB              LC_COLLATE=C              
#>  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
#>  [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
#>  [9] LC_ADDRESS=C               LC_TELEPHONE=C            
#> [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       
#> 
#> time zone: America/New_York
#> tzcode source: system (glibc)
#> 
#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base     
#> 
#> other attached packages:
#> [1] SOMNiBUS_1.12.0  BiocStyle_2.32.0
#> 
#> loaded via a namespace (and not attached):
#>   [1] jsonlite_1.8.8              magrittr_2.0.3             
#>   [3] magick_2.8.3                GenomicFeatures_1.56.0     
#>   [5] farver_2.1.1                rmarkdown_2.26             
#>   [7] BiocIO_1.14.0               zlibbioc_1.50.0            
#>   [9] vctrs_0.6.5                 memoise_2.0.1              
#>  [11] Rsamtools_2.20.0            DelayedMatrixStats_1.26.0  
#>  [13] RCurl_1.98-1.14             tinytex_0.50               
#>  [15] htmltools_0.5.8.1           S4Arrays_1.4.0             
#>  [17] AnnotationHub_3.12.0        curl_5.2.1                 
#>  [19] Rhdf5lib_1.26.0             SparseArray_1.4.0          
#>  [21] rhdf5_2.48.0                sass_0.4.9                 
#>  [23] bslib_0.7.0                 bsseq_1.40.0               
#>  [25] plyr_1.8.9                  cachem_1.0.8               
#>  [27] GenomicAlignments_1.40.0    lifecycle_1.0.4            
#>  [29] pkgconfig_2.0.3             Matrix_1.7-0               
#>  [31] R6_2.5.1                    fastmap_1.1.1              
#>  [33] GenomeInfoDbData_1.2.12     MatrixGenerics_1.16.0      
#>  [35] digest_0.6.35               colorspace_2.1-0           
#>  [37] AnnotationDbi_1.66.0        S4Vectors_0.42.0           
#>  [39] regioneR_1.36.0             GenomicRanges_1.56.0       
#>  [41] RSQLite_2.3.6               filelock_1.0.3             
#>  [43] fansi_1.0.6                 httr_1.4.7                 
#>  [45] abind_1.4-5                 mgcv_1.9-1                 
#>  [47] compiler_4.4.0              bit64_4.0.5                
#>  [49] withr_3.0.0                 BiocParallel_1.38.0        
#>  [51] DBI_1.2.2                   highr_0.10                 
#>  [53] HDF5Array_1.32.0            R.utils_2.12.3             
#>  [55] rappdirs_0.3.3              DelayedArray_0.30.0        
#>  [57] rjson_0.2.21                gtools_3.9.5               
#>  [59] permute_0.9-7               tools_4.4.0                
#>  [61] R.oo_1.26.0                 glue_1.7.0                 
#>  [63] restfulr_0.0.15             nlme_3.1-164               
#>  [65] rhdf5filters_1.16.0         grid_4.4.0                 
#>  [67] reshape2_1.4.4              generics_0.1.3             
#>  [69] gtable_0.3.5                BSgenome_1.72.0            
#>  [71] tzdb_0.4.0                  R.methodsS3_1.8.2          
#>  [73] tidyr_1.3.1                 data.table_1.15.4          
#>  [75] hms_1.1.3                   utf8_1.2.4                 
#>  [77] XVector_0.44.0              BiocGenerics_0.50.0        
#>  [79] BiocVersion_3.19.1          pillar_1.9.0               
#>  [81] stringr_1.5.1               limma_3.60.0               
#>  [83] splines_4.4.0               dplyr_1.1.4                
#>  [85] BiocFileCache_2.12.0        lattice_0.22-6             
#>  [87] rtracklayer_1.64.0          bit_4.0.5                  
#>  [89] tidyselect_1.2.1            locfit_1.5-9.9             
#>  [91] Biostrings_2.72.0           knitr_1.46                 
#>  [93] bookdown_0.39               IRanges_2.38.0             
#>  [95] SummarizedExperiment_1.34.0 stats4_4.4.0               
#>  [97] xfun_0.43                   Biobase_2.64.0             
#>  [99] statmod_1.5.0               annotatr_1.30.0            
#> [101] matrixStats_1.3.0           stringi_1.8.3              
#> [103] VGAM_1.1-10                 UCSC.utils_1.0.0           
#> [105] yaml_2.3.8                  evaluate_0.23              
#> [107] codetools_0.2-20            tibble_3.2.1               
#> [109] BiocManager_1.30.22         cli_3.6.2                  
#> [111] munsell_0.5.1               jquerylib_0.1.4            
#> [113] Rcpp_1.0.12                 GenomeInfoDb_1.40.0        
#> [115] dbplyr_2.5.0                png_0.1-8                  
#> [117] XML_3.99-0.16.1             parallel_4.4.0             
#> [119] ggplot2_3.5.1               readr_2.1.5                
#> [121] blob_1.2.4                  sparseMatrixStats_1.16.0   
#> [123] bitops_1.0-7                scales_1.3.0               
#> [125] purrr_1.0.2                 crayon_1.5.2               
#> [127] rlang_1.1.3                 KEGGREST_1.44.0

References

Kaiqiong Zhao, Lajmi Lakhal‐Chaieb, Karim Oualkacha. 2020. “A Novel Statistical Method for Modeling Covariate Effects in Bisulfite Sequencing Derived Measures of Dna Methylation.” Biometrics preprint. https://doi.org/10.1111/biom.13307.

Lakhal-Chaieb, Lajmi, Celia MT Greenwood, Mohamed Ouhourane, Kaiqiong Zhao, Belkacem Abdous, and Karim Oualkacha. 2017. “A Smoothed Em-Algorithm for Dna Methylation Profiles from Sequencing-Based Methods in Cell Lines or for a Single Cell Type.” Statistical Applications in Genetics and Molecular Biology 16 (5-6): 333–47.

Prochenka, Agnieszka, Piotr Pokarowski, Piotr Gasperowicz, Joanna Kosińska, Piotr Stawiński, Renata Zbieć-Piekarska, Magdalena Spólnicka, Wojciech Branicki, and Rafał Płoski. 2015. “A Cautionary Note on Using Binary Calls for Analysis of Dna Methylation.” Bioinformatics 31 (9): 1519–20.