tryCatch() function to save warning message AND error message in r - r

my previous question was:
I am simulating multilevel data and fitting it to various Multilevel models.
I want to make a function that if there is any error (such as "failed to converge" or "singular fit"), I want to save it.
For example, my model is
lmer(y~ x1 + x2 + (1|pid), data=sim_data).
and here are many conditions so various data will be fitted into this model.
How can I save the error or warning message as a whole in the dataframe or list?
(like, first dataset -> no error, second dataset -> converge error...etc)
and some people gave me good answer to it.
However, the answers to this question were about error message, but not warning message.
for( i in 1:10){
catch$error[i]<-tryCatch((y~ x1 + x2 + (1|pid), data=sim_data),
error=function(e) e$message,
warning=function(w) w$message)
}
with this code, can I extract warning and error message both?
and it seems like generating following error
Error in results$MLM0warning1[i] <- tryCatch(model_null(ind_sim_data), :
incompatible types (from S4 to character) in subassignment type fix

Related

Can't complete regression loop (invalid term in model formula)

I have applied the below code, and it was working fine until I got an error message that I don't know how to solve.
respvars <- names(QBB_clean[1653:2592])
`predvars <- c("bmi","Age", "sex","lpa2c", "smoking", "CholesterolTotal")`
results <- list()
for (v in respvars) {
form <- reformulate(predvars, response = v) results[[v]] <- lm(form, data = QBB_clean) } `
Error message:
Error in terms.formula(formula, data = data) :
invalid term in model formula
The error message "invalid term in model formula" says that there is something wrong with the way the formula is being constructed.
There might be several reasons. First, one of the variables in the formula may not present in the dataset or has a different name. To fix this issue, you can print the variable names in the formula and compare them to the variable names in the dataset.

How do I solve an error in x : non-conformable arguments (R)?

I am trying to implement ordinal logistic regression on my dataset in r. I use the function 'polr' for this, but cannot seem to find a lot of information regarding its implementation.
The following errors are the ones I'm stuck on:
> dat.polr <- polr(as.factor(relevance)~allterms+idf.title, data=dat.one)
Warning message:
In polr(as.factor(relevance) ~ allterms + idf.title + idf.desc + :
design appears to be rank-deficient, so dropping some coefs
> dat.pred <- predict(dat.polr,dat.test,type="class")
Error in X %*% object$coefficients : non-conformable arguments
I want to train my model to guess the relevance of a new dataset. dat.one is the dataset I'm using to train the data, dat.test is the dataset I'm using to test the data. I believe that the predict variable's error is caused by the warning in polr. However, I have no clue how to resolve this. Any help would be appreciated :)

R mlogit model, , missing value where TRUE/FALSE needed, 20 invalid factor level warnings

I'm trying to run a multinomial logistic regression using the mlogit package in R.
I've uploaded the data here https://drive.google.com/file/d/0B_o3xTWAYdbuRGw0dzNFRzd2NEk/view?usp=sharing.
The data contains two different choice variables which I want to run the same model on. I run the first model like so:
lfsm1 <- mlogit.data(lfs.models, shape="wide", choice="PWK")
f1 <- mFormula(PWK~1 | MIGGRP+SEX+AGE+EDU)
m1 <- mlogit(f1, lfsm1, weights=PWT14)
summary(m1)
This model runs without issues. Then I run the same exact model on the other choice variable:
lfsm2 <- mlogit.data(lfs.models, shape="wide", choice="multi")
f2 <- mFormula(multi~1 | MIGGRP+SEX+AGE+EDU)
m2 <- mlogit(f1, lfsm2, weights=PWT14)
I get the following errors:
Error in if (is.null(initial.value) || lnl <= initial.value) break :
missing value where TRUE/FALSE needed
In addition: There were 20 warnings (use warnings() to see them)
> warnings()
Warning messages:
1: In `[<-.factor`(`*tmp*`, is.na(x), value = FALSE) :
invalid factor level, NA generated
And that warning message repeats 20x.
I'm not sure what either of these errors mean in the context of my model. A previous post (mlogit: missing value where TRUE/FALSE needed) suggests that my first error occurs because my data are not in wide format, or because there are some individuals who do not select any of the alternatives. In my case neither of these explanations can be right. What I've seen about the warning messages suggest mlogit is reacting badly to variables being factors or numeric. But I don't quite understand why this would matter in a multinomial regression context, or how the problem only occurred twenty times in such a large dataset.
Any suggestions would be most appreciated!
Try
m2 <- mlogit(f2, lfsm2, weights=PWT14)
Note the f2 in the call to mlogit.
In your second call to mlogit.data, you have specified that multi is the choice variable, and the data are prepared accordingly. Yet, in the formula that you are using, f1, the dependent variable is specified as PWK, so that mlogit is expecting a dataframe with one row for each alternative as defined by PMK, not multi.

Why do I get "Error in as.character.default(<S4 object of class "glmerMod">)" when using tryCatch?

I am applying a linear model over a dataset, and using tryCatch to detect possible warnings, here's the script:
glm.m <- tryCatch(
glmer(y ~ gene + (1|x) + (1|z), data =a, family="binomial"),
warning= function(w){paste("warning",glmer(y ~ gene + (1|x) + (1|z), data =a, family="binomial"))})
I keep on getting this error message:
Error in as.character.default() : no
method for coercing this S4 class to a vector
which does disappear if I remove tryCatch and simply run the model. Unfortunately I need to use tryCatch to detect the rows which will give me warnings.
Did anyone already encounter the same error in similar conditions? I did see other threads with similar errors, but nothing was helpful for my case.

Error for predict() with lmer

I'm using a leave-one-out method to evaluate how well a model with one datapoint excluded predicts that datapoint (rotating through all datapoints). The code below has successfully run on essentially the same data with a slightly different DV, so I'm stumped as to why I'm getting the error that I'm getting. Here's the relevant chunk of code:
dataPennTrim.lmer <- lmer(logDur.PENN~cNewNounDen*ContextCode+
Vowel.Contrasts+BlockCode+
(1|subject)+(0+ cNewNounDen +ContextCode|subject)+
(1|word)+(0+ContextCode|word),
data=pennTrim,
control = lmerControl(optimizer = "bobyqa"),REML=FALSE)
pennPred <- predict(dataPennTrim.lmer, newdata = dataFull2)
dataFull2 has the same columns as pennTrim, it just has more rows. Pretty standard use of the predict() function. I get this error:
Error in t(.Call(Csparse_dense_crossprod, y, x)) :
error in evaluating the argument 'x' in selecting a
method for function 't': Error: Cholmod error 'X and/or Y
have wrong dimensions' at file ../MatrixOps/cholmod_sdmult.c, line 90
Any thoughts about what might be causing this error? I can use essentially the same code with the same dataframes swapping out logDur.PENN for logDur.Manual (measurements from a different source) and the code gives no errors.

Resources