Skip to content

Commit

Permalink
Discrepancy in residual variance between VarCorr() and get_variance_r…
Browse files Browse the repository at this point in the history
…esidual()

Fixes #929
  • Loading branch information
strengejacke committed Nov 5, 2024
1 parent a4d1003 commit c736fd0
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
3 changes: 1 addition & 2 deletions R/get_sigma.R
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ get_sigma <- function(x, ci = NULL, verbose = TRUE) {
dat <- as.data.frame(x)
sigma_column <- grep("sigma", colnames(dat), fixed = TRUE)
if (length(sigma_column) == 1) {
mean(dat[[sigma_column]][1])
mean(dat[[sigma_column]])
} else if (length(sigma_column)) {
# if more than one sigma column,
# there isn't a traditional sigma for the model
Expand All @@ -226,7 +226,6 @@ get_sigma <- function(x, ci = NULL, verbose = TRUE) {
NULL
}
)

# compute sigma manually ---------------
if (is_empty_object(s)) {
# default sigma ---------------
Expand Down
14 changes: 14 additions & 0 deletions tests/testthat/test-brms.R
Original file line number Diff line number Diff line change
Expand Up @@ -921,3 +921,17 @@ test_that("get_variance works", {
# make sure it's a matrix
# expect_true(is.matrix(get_modelmatrix(null_model(mdl))))
})


# get variance
test_that("get_variance aligns with get_sigma", {
skip_if_not_installed("lme4")
mdl <- brms::brm(mpg ~ hp + (1 | cyl), data = mtcars, seed = 123)
VC <- lme4 <- VarCorr(mdl)
out1 <- VC$residual__$sd[1, 1]^2 # Residual variance
out2 <- get_variance(mdl)$var.residual
out3 <- get_sigma(mdl)^2
expect_equal(out1, out2, tolerance = 1e-3, ignore_attr = TRUE)
expect_equal(out1, out3, tolerance = 1e-3, ignore_attr = TRUE)
expect_equal(out2, out3, tolerance = 1e-3, ignore_attr = TRUE)
})

0 comments on commit c736fd0

Please sign in to comment.