【问题标题】:trycatch scope in RR中的trycatch范围
【发布时间】:2021-12-27 03:39:24
【问题描述】:

以下代码行为不端。当我在 RStudio 中运行它来测试它时,它很好。我得到了一个有意义的 custom_vars 值。一旦我尝试使用 Knit 运行此代码,它每次都会返回错误。

我尝试过使用 custom_vars 的范围来玩 aorund,但这也不起作用。

report_params <- "-summary-private-room-tenure-minmax-map-Analyse newVar group-Analyse oldVar group"

custom_vars <- tryCatch(
{
  a <- report_params
  a <- as.list(strsplit(a, "-")[[1]])
  a <- str_subset(a, pattern = "Analyse.*.group")
  
  if (length(a) > 0) {
    a <- sapply(strsplit(a, split=' group'  , fixed=TRUE), function(x) (x[1]))
    a <- sapply(strsplit(a, split='Analyse ', fixed=TRUE), function(x) (x[2]))
    custom_vars <- c(a)   # no return in try code!
  } else {
    ret <- c("zero legth")
    return( ret ) 
  }
}, error=function(e) {
    ret <- c("error")
    return( ret ) 
  }
)

如果我去掉 trycatch,它会再次正常工作。我已经尝试了我能想到的一切。这毫无意义。

  a <- params$report_params
  a <- as.list(strsplit(a, "-")[[1]])
  a <- stringr::str_subset(a, pattern = "Analyse.*.group")
  
  if (length(a) > 0) {
    a <- sapply(strsplit(a, split=' group'  , fixed=TRUE), function(x) (x[1]))
    a <- sapply(strsplit(a, split='Analyse ', fixed=TRUE), function(x) (x[2]))
    custom_vars <- c(a)   # no return in try code!
  } else {
    custom_vars <- c("zero legth")
    # return( ret ) 
  }

【问题讨论】:

    标签: r r-markdown


    【解决方案1】:

    这不是function,不需要returnreturn 导致错误触发tryCatch 中的error 函数。

    custom_vars <- tryCatch({
        a <- report_params
        a <- as.list(strsplit(a, "-")[[1]])
        a <- stringr::str_subset(a, pattern="Analyse.*.group")
        if (length(a) > 0) {
          a <- sapply(strsplit(a, split=' group', fixed=TRUE), function(x) x[1])
          sapply(strsplit(a, split='Analyse ', fixed=TRUE), function(x) x[2])
        } else {
          "zero legth"
        }
      }, error=function(e) "error")
    
    custom_vars
    # [1] "newVar" "oldVar"
    

    【讨论】:

    • 你是对的。我没有注意到这一点,因为该执行路径从未执行过。看来语法错误还是导致了错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-20
    相关资源
    最近更新 更多