Skip to content

Commit 9d0cf9a

Browse files
committed
Error-trap formulas with a LHS in LINPRED
1 parent 6835e72 commit 9d0cf9a

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

R/LINPRED.R

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ function(stoch, LHS, formula, link=NULL, coefPrefix=quote(beta_),
4545
noncenter = FALSE, centerVar=NULL, modelInfo, .env){
4646

4747
# Make sure formula is in correct format
48-
formula <- stats::as.formula(formula)
48+
formula <- check_formula(formula)
4949

5050
# Get index range on LHS to use if the RHS formulas do not specify them
5151
LHS_ind <- extractBracket(LHS)
@@ -136,8 +136,7 @@ function(formula, coefPrefix=quote(beta_), sdPrefix=NULL, priorSpecs=setPriors()
136136
modMatNames=FALSE, noncenter = FALSE, centerVar=NULL, modelInfo, .env){
137137

138138
# Make sure formula is in correct format
139-
if(formula[[1]] != quote(`~`)) formula <- c(quote(`~`),formula)
140-
formula <- stats::as.formula(formula)
139+
formula <- check_formula(formula)
141140

142141
# Evaluate prior settings
143142
priorSpecs <- eval(priorSpecs, envir=.env)
@@ -171,6 +170,16 @@ use3pieces=FALSE,
171170
unpackArgs=TRUE
172171
)
173172

173+
# Check validity of formula
174+
check_formula <- function(formula){
175+
if(formula[[1]] != quote(`~`)) formula <- c(quote(`~`),formula)
176+
formula <- stats::as.formula(formula)
177+
if(length(formula) > 2){
178+
stop("check_formula: Formula should be RHS-only, such as ~1 or ~x, but not y~x",
179+
call.=FALSE)
180+
}
181+
formula
182+
}
174183

175184
# This function starts with a formula plus options
176185
# Splits the formula into separate components (terms)

tests/testthat/test_LINPRED.R

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,22 @@ test_that("LINPRED basic fixed effects models", {
386386
nimbleOptions(enableMacroComments = TRUE)
387387
})
388388

389+
test_that("LINPRED error traps LHS in formula", {
390+
nimbleOptions(enableMacroComments = FALSE)
391+
set.seed(123)
392+
modInfo <- list(constants=list(y = rnorm(10), x=round(rnorm(10), 3), n = 10))
393+
394+
# Missing LHS error trapping must be handled by buildMacro() in nimble
395+
396+
# LHS in formula
397+
code <- quote(mu[1:n] <- LINPRED(y~1))
398+
399+
expect_error(
400+
LINPRED$process(code, modelInfo=modInfo, environment()),
401+
"Formula should be RHS-only"
402+
)
403+
404+
})
389405

390406
test_that("LINPRED with uncorrelated random effects", {
391407
nimbleOptions(enableMacroComments = FALSE)

0 commit comments

Comments
 (0)