Erica
Erica

Reputation: 125

How to automatically skip over errors in r

I'm trying to create new variables from some output from a number of two-piece segmented regression models that I'm running. The code for my new variable is:

initial1=c(fmod$psi[1],fmod2$psi[1], fmod3$psi[1], fmod4$psi[1], fmod5$psi[1], fmod6$psi[1], fmod7$psi[1], fmod8$psi[1], fmod9$psi[1], fmod10$psi[1], fmod11$psi[1],fmod12$psi[1], fmod13$psi[1], fmod14$psi[1], fmod15$psi[1], fmod16$psi[1], fmod17$psi[1], fmod18$psi[1], fmod19$psi[1], fmod20$psi[1], fmod21$psi[1],fmod22$psi[1], fmod23$psi[1], fmod24$psi[1], fmod25$psi[1], fmod26$psi[1], fmod27$psi[1], fmod28$psi[1], fmod29$psi[1], fmod30$psi[1], fmod31$psi[1],fmod32$psi[1], fmod33$psi[1], fmod34$psi[1], fmod35$psi[1], fmod36$psi[1], fmod37$psi[1], fmod38$psi[1], fmod39$psi[1], fmod40$psi[1], fmod41$psi[1],fmod42$psi[1], fmod43$psi[1], fmod44$psi[1], fmod45$psi[1], fmod46$psi[1], fmod47$psi[1], fmod48$psi[1], fmod49$psi[1], fmod50$psi[1], fmod51$psi[1],fmod52$psi[1], fmod53$psi[1], fmod54$psi[1], fmod55$psi[1], fmod56$psi[1], fmod57$psi[1], fmod58$psi[1], fmod59$psi[1], fmod60$psi[1], fmod61$psi[1], fmod62$psi[1], fmod63$psi[1], fmod64$psi[1])

where fmod, fmod2, fmod3, etc. are my regression models. Some of the regression models have errors and do not produce output (because the initial breakpoint estimates are too close to each other). Because of that, when I try to make my 'initial1' variable, I get error messages such as:

Error: object 'fmod12' not found

and the 'initial' variable is not created. I would like these models that don't have output associated with them to be automatically skipped over, or to be replaced with 'NA'. Does anyone know how to do this?

Upvotes: 0

Views: 66

Answers (1)

user3603486
user3603486

Reputation:

You're creating many different models and giving them numbered names. Why not put them in a list instead?

At model creation time:

for (i in 1:lots) fmod[[i]] <- my_segmented_reg(...)

where my_segmented_reg presumably returns either a model, or NULL or NA.

Then you have a list fmod which you can start using straight away.

Upvotes: 2

Related Questions