Calculating R-square values for two LME models with R

Calculating Rvalues cannot be done immediately (as far as we’ve looked) in R for LME models. Thanks to Corine Horsch we followed a method found in this book and created two functions to immediately calculate R2, which you can see below:

getRSquare <- function(Model0, Model1){

  sigma0SQ <-Model0$sigma^2
  tau0SQ <- diag(sqrt(getVarCov(Model0)))^2
  sigma1SQ <-Model1$sigma^2
  tau1SQ <- diag(sqrt(getVarCov(Model1)))^2

  Rsquare <- 1 - ((sigma1SQ+tau1SQ)/(sigma0SQ+tau0SQ))

  return (Rsquare)


In models with nested random effects, the function getVarCov() may not work. We then have to resort to a sneakier way of getting the tau value, using the more generic varCorr() function:

vc.Model0 <- VarCorr(Model0)
tau0SQ <- as.numeric(vc.Model0[4,2])^2
vc.Model1 <- VarCorr(Model1)
tau1SQ <- as.numeric(vc.Model1[4,2])^2

Note here that we are accessing a table at a certain cell: [4,2]. If you print vc.Model0 or vc.Model1 out, the cell at the 4th row/2nd column corresponds exactly to the tau value relevant to the inner nested random effect. To get the outer one for example, you should use cell [2,2]. Experiment with this table to understand better how to access the right cell for models with several nested random effects.