R: Glmer Model Error - r

By run of follow code in R:
m3 <- glmer(accoccur ~ Time + Year + Month + holiday + HolidayNum + (1 + Time | DistfKaraj) , data = accident, family = "binomial" , nAGQ =1)
Run stooped with this error:
Error in intI(i, n = x#Dim[1], dn[[1]], give.dn = FALSE) :
"anyNA" is not a BUILTIN function

anyNA() is a function that was introduced in R 3.1.0 -- search http://cran.r-project.org/src/base/NEWS for the function name. My guess is that you have the development version of lme4 (hosted here), which makes use of anyNA() (based on the blame, it was added in November 2014), but doesn't define it for you.
You have a few options:
Upgrade to at least R 3.1.0 -- current is 3.2.0.
Define anyNA() yourself, with anyNA <- function(x) any(is.na(x))
I'd recommend at least upgrading your version of R, unless you rely on packages that are unavailable in future versions.

Related

Failing to produce glmmTMB diagnostics plots with package DHARMa

I have tried to produce diagnostics plots for glmmTMB models using package DHARMa without success. Example 1.1 in this vignette gives:
owls_nb1 <- glmmTMB(SiblingNegotiation ~ FoodTreatment*SexParent +
(1|Nest)+offset(log(BroodSize)),
contrasts=list(FoodTreatment="contr.sum",
SexParent="contr.sum"),
family = nbinom1,
zi = ~1,
data=Owls)
plot(owls_nb1_simres <- simulateResiduals(owls_nb1) )
# Error in on.exit(add = TRUE, { : invalid 'add' argument
The same happens with:
if (!require(RCurl)) install.packages('RCurl'); library(RCurl)
unicorns <- read.csv(text= RCurl::getURL("https://raw.githubusercontent.com/marcoplebani85/datasets/master/unicorns.csv"))
# simulated data, obviously
unicorns_glmmTMB <- glmmTMB(Herd_size_n ~ food.quantity
+ (1 + food.quantity | Locality)
+ (1 + food.quantity | Year_Month),
family="poisson",
data=unicorns)
plot(simulateResiduals(unicorns_glmmTMB))
# Error in on.exit(add = TRUE, { : invalid 'add' argument
If I run the same model in lme4::glmer:
unicorns_glmer <- glmer(Herd_size_n ~ food.quantity
+ (1 + food.quantity | Locality)
+ (1 + food.quantity | Year_Month),
family="poisson",
data=unicorns)
...and "feed" it to:
plot(simulateResiduals(unicorns_glmer))
I obtain diagnostics plots without issues (by the way I am aware that model unicorns_glmer is suboptimal and can be improved).
I'm using:
glmmTMB version 1.0.2.9000 freshly installed from github;
DHARMa version 0.4.1;
R version 3.6.3;
MacOS Sierra version 10.12.6.
Has anyone encountered the same problem? Does anyone know how to solve it?
EDIT: my question was originally on how packages performance and DHARMa handle glmmTMB objects. For the sake of focus and clarity I removed the references to package performance, thus making this question specific to glmmTMB and DHARMa.
It looks like this is a bug that was present in R <= 4.0.1. From the R NEWS file for version 4.0.2:
on.exit() now correctly matches named arguments, thanks to PR#17815 (including patch) by Brodie Gaslam.
I have attempted to fix the glmmTMB code so it works around the bug.
You could try
remotes::install_github("glmmTMB/glmmTMB/glmmTMB#on_exit_order")
and see if that helps (provided nothing goes wrong, this branch should be merged into master shortly ...)

slice_plot() could not find function error

I'm following the book "Computer-age Calculus with R" but cannot run the function slice_plot( which is the first one used for graphing functions). The library mosaic, mosaicCalc and mosaicModel are installed. I don't know what I'm missing.
this is the code with the libraries required by the book:
library(mosaic)
library(mosaicCalc)
library(mosaicModel)
library(akima)
drug_remaining <- function(dose, duration, time_constant){
dose * exp(-duration / time_constant)
}
slice_plot(
drug_remaining(dose = 100, time_constant = 4, duration = t) ~ t,
domain(t = 0:20))
I've found the function slice_plot() and countour_plot() are still in development in a beta version of the mosaicCalc package, to use them we need to install the beta version running this code:
remotes::install_github("ProjectMOSAIC/mosaicCalc", ref="beta")
https://github.com/ProjectMOSAIC/mosaicCalc/issues/4

Huber-White robust standard errors for a GLMM - R

I have discovered some heteroscedasticity in my model that I would like to compensate for with more robust standard errors. I have tried to use the Huber-White robust standard errors from the merDeriv package in R but I beleive these only work for a GLMM with a binomial distribution. Is there a way I could achieve the same thing for a Negative Binomial distribition?
Model:
library(lme4)
model <- glmer.nb(Jobs ~ 1 + Month + Year + (1|Region), data = df)
Huber-White robust standard errors:
library(merDeriv)
bread.glmerMod(model)
Error:
Error in vcov.lmerMod(object, full = full) : estfun.lmerMod() only works for lmer() models.
Thank you for any help!
This looks like a bug in the package, as far as I can tell (the bread.glmerMod function was calling estfun.lmerMod rather than estfun.glmerMod; there's a broader question here about the design of the generic functions, but never mind ...)
You should be able to install a fixed version from my fork via remotes::install_github("bbolker/merDeriv"), then reload the package and try again.
Alternately, download the tarball, change vcov.lmerMod to vcov.glmerMod in the last line of R/bread.glmerMod.R, and re-install the package ...
Try something like this:
library(lme4)
model <- glmer.nb(Jobs ~ 1 + Month + Year + (1|Region), data = df)
cov <- vcovHC(model, type = "HC1", sandwich = T)
se <- sqrt(diag(cov_m1))
(Can't confirm if it works since this there isn't a reproducible example)

Error in lme4::allFit() -- no applicable method for 'isGLMM'

I'm hitting a confusing error while trying to run the lme4::allFit() using some built-in parallelization. I fit an initial model m0, which uses a larger dataframe ckDF (n = 265,623 rows) to model a binary response to a number of categorical and continuous predictors in a logistic framework with a random intercept for year.
I'm interested in determining whether different optimizers yield different results, following some recommendations I've found online (e.g. by #BenBolker here). My data is fairly large and takes ~20 minutes to run usually, so I'm hoping to use the parallel and ncpus parameters of allFit() to speed it up a bit. Here's my relevant code:
require(lme4)
require(parallel)
m0 <- glmer(returned ~ 1 + barge + site + barge:site +
(run + rearType + basin)^2 +
(tdg + temp + holdingTime)^2 +
(1|year),
data = ckDF, family = 'binomial',
control = glmerControl(optimizer='bobyqa',
optCtrl = list(maxfun = 1e5)))
af1 <- allFit(m0, parallel = 'multicore', ncpus = detectCores())
Upon doing this, I encounter the following error:
Error in checkForRemoteErrors(val) :
7 nodes produced errors; first error: no applicable method for 'isGLMM' applied to an object of class "list"
Any ideas? It seems to me that when it constructs a bunch of nodes, somehow some of them don't import the lme4 package and thus do not recognize isGLMM(); but I don't know why allFit() would do this, since it's from lme4(). I tried looking under the hood and altering the function for my own allFit() package, but ran into other errors.
Any help would be appreciated. R Version: 3.6.1; lme4 Version: 1.1-21; platform: Windows 10 64-bit
Thanks to #user20650 & #Ben Bolker for the tips in comments above -- it worked and I was able to get allFit() to run as expected, by ensuring I use parallel = "snow" in my function call since I'm running in Windows. Just posting the edited code here for anyone else who finds this useful:
require(lme4); require(snow)
# Define initial model (switched to defaults here)
m0 <- glmer(returned ~ 1 + barge + site + barge:site +
(run + rearType + basin)^2 +
(tdg + temp + holdingTime)^2 +
(1|year),
data = ckDF, family = 'binomial')
# Set up cluster for running allFit()
optCls <- makeCluster(detectCores()-1, type = "SOCK")
clusterEvalQ(optCls,library("lme4"))
clusterExport(optCls, "ckDF")
# Use allFit() to look at differences in optimizers
system.time(af1 <- allFit(m0, parallel = 'snow',
ncpus = detectCores()-1, cl=optCls))
stopCluster(optCls)
Ended up taking ~40 minutes using 11 cores on my machine.

IV Regression in R - could not find function "linearHypothesis"

I am very new to R, and trying to reproduce a Stata Output. I have the following Regression
formula2 <- as.formula(paste("lnwd ~ dreformd + ", paste("", PredictorVar2, collapse='+'), "+", paste("", PredictorYr, collapse='+')))
with dreformd being endogenous. I want to run a 2SLS by regressing dreformd on three instruments
datatwo$qz1 <- factor (with (datatwo, ifelse ((q1 == 1), 1, 0)))
datatwo$qz2 <- factor (with (datatwo, ifelse ((q1 == 2), 1, 0)))
datatwo$qz3 <- factor (with (datatwo, ifelse ((q1 == 0|q1 == 3), 1, 0)))
This would be my code:
library(car)
iv = ivregress(formula2, dreformd ~ qz1 + z2 + qz3, datatwo)
And all I get as Output is
Error in ivregress(formula2, dreformd ~ qz1 + qz2 + qz3, datatwo) :
could not find function "linearHypothesis"
I am lost here, I've tried everything and have no clue where the problem is. I've also tried using the ivreg function, but R cannot find that one either. The AER and CAR packages are installed. What am I missing ?
EDIT: tried installing CAR and AER with dependencies, still get the same error. The car package cannot load, and there is no pbkrtest package. Tried installing it, I get this error:
Warning in install.packages :
package ‘pbkrtest’ is not available (for R version 3.2.1)
I was struggling with this too.
You have to install car. R is going to ask you to install several other packages in the process. I went one by one (as far as I remember there were 7 or 8 different packages) and at the end could run library(car) and then R accept the function linearHypothesis

Resources