【问题标题】:How to get the return value if an R function has an error如果 R 函数有错误,如何获取返回值
【发布时间】:2014-04-17 00:51:11
【问题描述】:

我想在R中测试一个矩阵是否是奇异的。我尝试了一个函数,它是

is.non.singular.matrix()matrixcalc 包中。

但是,有时,在我的例子中,会生成一个 60*60 的矩阵,函数返回 FALSE,这意味着矩阵是奇异的。但我仍然可以使用solve() 来获得矩阵的反转。我应该相信哪一个?还有其他更好的方法吗?

或者,对于奇异矩阵,solve() 将返回错误消息。有没有办法写一个语句,如果solve() 返回错误,然后做其他事情(例如,为对角线元素添加一些变化)。但是我不知道如何获取错误信息的返回值。

【问题讨论】:

    标签: r matrix matrix-inverse singular


    【解决方案1】:

    测试try()是否返回类“try-error”的对象:

     mtx <- matrix(c(1,1,2,2), 2)
     if ( inherits( try( solve(mtx), silent=TRUE),  "try-error")){"oops"} else {solve(mtx)}
    [1] "oops"
    
    > if ( inherits( try( solve(mtx), silent=TRUE),  "try-error")){
                                         print("oops"); solve(mtx+ rnorm(4) )
                                        } else {solve(mtx)}
    [1] "oops"
               [,1]      [,2]
    [1,]  0.8310745 -1.618425
    [2,] -1.0580812  3.050279
    

    您可以想象将其构建为递归函数。见:

    ?Recall
    

    【讨论】:

    • 现在不再使用 try() 函数。这很棒。十分感谢。我会检查更多关于这些功能的信息。
    • 你能告诉我更多关于继承的信息吗? R 菜单不是那么容易理解...
    • 是的。使用class(try(solve(mtx))) 很容易看到。 inherits(x, "class_name") 使用起来比 class(x)=="class_name" 更安全
    猜你喜欢
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 2020-03-03
    • 2014-05-04
    • 1970-01-01
    相关资源
    最近更新 更多