简体   繁体   English

有没有办法在不使用try()或tryCatch()的情况下在错误后继续R中的for循环

[英]Is there a way to continue a for loop in R after an error without using try() or tryCatch()

I'm running a list of strings though an API for an NLP processing. 我正在通过用于NLP处理的API运行字符串列表。 Sometimes the number of tokens is too short and the API returns an error. 有时令牌数量太短,API返回错误。 I've already excluded smaller strings, but sometimes there's an inconsistency (for example what I deem quickly to be a token is rejected by the API). 我已经排除了较小的字符串,但是有时会出现不一致的情况(例如,我认为迅速成为令牌的内容被API拒绝了)。 There are only a few, but it's a very long list and I want to let it run through the night without checking on it every once in a while. 只有少数几个,但是列表很长,我想让它运行一整夜,而不必不时检查一下。

So that's why I need for the loop to continue even after an error. 因此,这就是为什么即使出现错误后我也需要循环继续的原因。

So I already fixed the problem but it's not optimal, I used the try command to check if there is an error: 所以我已经解决了这个问题,但是它不是最佳的,我使用try命令检查是否有错误:

for(i in 1:nrow(df){
#First I've filtered out what content is clearly too short:
  if(sapply(strsplit(df$Content[i], " "), length) > 19){

    res <- try(temp_analysis <- gl_nlp(df$Content[i], language = "en"))
    if(inherits(res, "try-error"))

    {      
      next
    }

    temp_analysis <- gl_nlp(df$Content[i], language = "en")

    And then some other stuff here

  }
}

This works quite fine, but the problem is that it access the API twice and is thus slower and bills me twice. 这工作得很好,但是问题在于它两次访问API,因此速度较慢,并且向我收费两次。

So is there a way to get this same effect, but without using the try command? 那么有没有办法获得相同的效果,却不使用try命令? Or a derivative of this command that doesn't actually need to call on the API first? 还是实际上不需要先调用API的此命令的派生形式?

Thanks in advance. 提前致谢。

You don't need to access the API twice with try . 您无需使用try两次访问API。 Here is a simple example: 这是一个简单的示例:

res <- try(a)
#Error in try(a) : object 'a' not found
class(res)
#[1] "try-error"

a <- 1
res <- try(a)
res
#[1] 1

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

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