有没有办法让 R 脚本在收到错误消息后继续而不是停止执行? [英] Is there any way to have R script continue after receiving error messages instead of halting execution?

查看:27
本文介绍了有没有办法让 R 脚本在收到错误消息后继续而不是停止执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在为学校的一个项目运行 ANOVA,该项目有大量可能的运行(1400 次左右),但其中一些无法在 R 中运行 ANOVA.我编写了一个脚本来运行所有 ANOVA,但其中一些不会运行并且 Rout 文件给了我contrasts<-(*tmp*, value = "contr.treatment") 中的错误:对比只能应用于具有 2 个或更多水平的因素调用: aov ... model.matrix -> model.matrix.default -> contrasts<-执行停止

I am currently running ANOVA for a project at school that has a large number of possible runs (1400 or so) but some of them aren't able to run ANOVA in R. I wrote a script to run all the ANOVA's, but some of them will not run and the Rout file gives me Error in contrasts<-(*tmp*, value = "contr.treatment") : contrasts can be applied only to factors with 2 or more levels Calls: aov ... model.matrix -> model.matrix.default -> contrasts<- Execution halted

有没有什么办法可以编写脚本,让 R 在出现错误的情况下继续执行脚本?

Is there any way to write the script that will make R continue the script despite the error?

我的整个脚本,除了文件加载、附加、创建接收器、库加载等......

My entire script, other then the file loading, attaching, creating a sink, library loading, etc is...

ss107927468.model<-aov(Race.5~ss107927468, data=snp1)
summary(ss107927468.model)

任何帮助将不胜感激.

推荐答案

查看函数 try() 及其帮助页面 (?try).您将 R 表达式包装在 try() 调用中,如果调用成功,则生成的对象在本例中包含拟合模型.如果失败,则返回一个带有 "try-error" 类的对象.这使您可以轻松检查哪些模型有效,哪些无效.

See the function try() and it's help page (?try). You wrap your R expression in a try() call and if it succeeds, the resulting object contains, in this case, the fitted model. If it fails, then an object with class "try-error" is returned. This allows you to easily check which models worked and which didn't.

您可以进行测试以决定是打印模型的摘要还是仅打印失败消息,例如:

You can do the testing to decide whether to print out the summary for the model or just a failure message, e.g.:

ss107927468.model <- try(aov(Race.5~ss107927468, data=snp1))
if(isTRUE(all.equal(class(ss107927468.model), "try-error"))) {
    writeLines("Model failed")
} else {
    summary(ss107927468.model)
}

这篇关于有没有办法让 R 脚本在收到错误消息后继续而不是停止执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆