How to skip an error in a loop

前端 未结 4 1254
庸人自扰
庸人自扰 2020-12-05 00:36

I want to skip an error (if there is any) in a loop and continue the next iteration. I want to compute 100 inverse matrices of a 2 by 2 matrix with elements randomly sampled

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 01:33

    The documentation for try explains your problem pretty well. I suggest you go through it completely.

    Edit: The documentation example looked pretty straightforward and very similar to the op's question. Thanks for the suggestion though. Here goes the answer following the example in the documentation page:

    # `idx` is used as a dummy variable here just to illustrate that
    # all 100 entries are indeed calculated. You can remove it.
    set.seed(1)
    mat_inv <- function(idx) {
        print(idx)
        x <- matrix(sample(0:2, 4, replace = T), nrow = 2)
        solve(x)
    }
    inverses <- lapply(1:100, function(idx) try(mat_inv(idx), TRUE))
    

提交回复
热议问题