简体   繁体   English

如果 R 循环中有错误,则返回 NA 或零并继续循环

[英]If there's an error in an R loop, return NA or zero and continue with the loop

I'm building an R Shiny App and it gets very cumbersome when errors are introduced.我正在构建一个 R Shiny 应用程序,当引入错误时它会变得非常麻烦。 I have a dataframe and I am looping through the rows using an NLS function and returning the EC50 value.我有一个 dataframe 并且我正在使用 NLS function 循环遍历行并返回 EC50 值。 The EC50 are then added to the original dataframe to display.然后将 EC50 添加到原始 dataframe 中进行显示。 Not every observation will fit so it returns an error and the app breaks.并非每个观察都适合,因此它会返回错误并且应用程序会中断。

What I would like is a way to return a NA or 0 when there are errors and for the loop to move on to other observations.我想要的是一种在出现错误时返回 NA 或 0 并让循环继续进行其他观察的方法。 A simple example of the code would be代码的一个简单示例是

df <- data.frame(x = c(1,2,3), y = rep('hi',3))

addition <- function(a,b){
  result <- a+b
  return(result)
}

df$z <- 1
for (i in 1:length(df$x)){
  df$z[i] <- addition(df$x[i], df[i,i])
}

The results I would like is as below:我想要的结果如下:

x X y是的 z z
1 1 hi你好 2 2
2 2 hi你好 NA不适用
3 3 hi你好 6 6

This is just a sample.这只是一个示例。 What I'm doing is more complicated but I want to return NA/0 with any types of error, and since it's user uploaded files, I wouldn't be able to know which index the error is going to be in.我正在做的事情更复杂,但我想返回 NA/0 任何类型的错误,并且由于它是用户上传的文件,我无法知道错误将出现在哪个索引中。

You could use tryCatch here.你可以在这里使用tryCatch When an error is caught, it can simply return an NA ;当捕获到错误时,它可以简单地返回一个NA otherwise it returns the result of the calculation:否则返回计算结果:

df <- data.frame(x = c(1,2,3), y = rep('hi',3))
df$z <- 1

for (i in 1:length(df$x)){
   df$z[i] <- tryCatch(
    addition(df$x[i], df[i,i]), 
    error = function(e) return(NA)
    )
}

df
#>   x  y  z
#> 1 1 hi  2
#> 2 2 hi NA
#> 3 3 hi  4

Created on 2022-08-10 by the reprex package (v2.0.1)代表 package (v2.0.1) 于 2022 年 8 月 10 日创建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM