Using limma, calculate the R squared from a matrix using nested models

getR2(p, mod, mod0 = NULL)

Arguments

p

A matrix that will be passed to lmFit object.

mod

A model matrix for the alternative model (the larger one).

mod0

A model matrix for the null model (the smaller one). If NULL then p will be used to calculate the residual sum of squares of the null model.

Value

A data.frame with the R squared and the adjusted R squared.

Author

Andrew E Jaffe, Leonardo Collado-Torres (examples)

Examples


## Define a model generating function for 30 'samples'
set.seed(20190827)
model_fun <- function(x) {
    ## Baseline + a group effect (2 groups) + a second covariate effect
    rnorm(30) +
        c(rnorm(15, mean = 3), rnorm(15, mean = 1)) +
        c(
            rnorm(5, sd = 0.5), rnorm(5, sd = 0.2, mean = 0.5),
            rnorm(5, sd = 0.2, mean = 0.9)
        )
}

## Generate the data for 20 'genes'
p <- t(sapply(seq_len(20), model_fun))

## Define the phenotype data for these 30 'samples'
pheno <- data.frame(
    group = rep(c("A", "B"), each = 15),
    batch = rep(seq_len(3), each = 5)
)

## Define a full model
mod <- with(pheno, model.matrix(~ group + batch))
## and compute the R2 for each 'gene'
getR2(p, mod)
#>           R2 Adjusted_R2
#> 1  0.3193878  0.26897212
#> 2  0.2945847  0.24233173
#> 3  0.4793508  0.44078420
#> 4  0.3372094  0.28811380
#> 5  0.6036615  0.57430311
#> 6  0.5507361  0.51745728
#> 7  0.5047045  0.46801592
#> 8  0.1524957  0.08971761
#> 9  0.4873594  0.44938607
#> 10 0.5588035  0.52612224
#> 11 0.5303283  0.49553784
#> 12 0.4992324  0.46213855
#> 13 0.2818108  0.22861165
#> 14 0.5256746  0.49053940
#> 15 0.1703795  0.10892608
#> 16 0.5461353  0.51251568
#> 17 0.4942185  0.45675322
#> 18 0.4395134  0.39799584
#> 19 0.5381213  0.50390804
#> 20 0.3463855  0.29796957

## Define a smaller model
mod0 <- with(pheno, model.matrix(~group))
## And now compute the new R2 for each 'gene'
getR2(p, mod, mod0)
#>             R2  Adjusted_R2
#> 1  0.085617776  0.017885759
#> 2  0.003342680 -0.070483788
#> 3  0.076400642  0.007985875
#> 4  0.158359191  0.096015427
#> 5  0.187068236  0.126851068
#> 6  0.102305808  0.035809942
#> 7  0.084633451  0.016828522
#> 8  0.025949008 -0.046202917
#> 9  0.229978202  0.172939551
#> 10 0.070306664  0.001440491
#> 11 0.005686813 -0.067966016
#> 12 0.042070317 -0.028887437
#> 13 0.061646038 -0.007861663
#> 14 0.076929068  0.008553443
#> 15 0.011072472 -0.062181419
#> 16 0.030363946 -0.041460947
#> 17 0.127341788  0.062700439
#> 18 0.018024462 -0.054714466
#> 19 0.081112288  0.013046532
#> 20 0.261492796  0.206788559