【问题标题】:`The standard deviation is zero` error with cor function calling in group_by在 group_by 中调用 cor 函数的“标准偏差为零”错误
【发布时间】:2019-01-11 22:31:27
【问题描述】:
df <- data.frame(Tag = c(1, 1, 1, 1, 2, 2, 2, 2),
             x = c(9,7,3,2,1,1,1,1),
             y = c(1,2,3,4,1,2,3,4))

cor_fun<- function(x,y){
           val <- cor(x,y)
           return(val)}

df %>%
group_by(Tag) %>%
  summarise(c = cor_fun(x,y))

这里我们试图通过group_by(Tag)计算xy之间的相关性。问题是当我们计算x和y的相关性时,任何一列的标准偏差为0的错误 the standard deviation is zero 这在生产中是不可接受的。所以我除了the standard deviation is zero 发生时,函数应该返回x 的平均值,否则应该返回相关输出。我已经尝试重现下面粘贴的相同场景,请指导我。 在函数名称cor_fun 中使用try-catch

简要要求

  1. 在Function里面,我们可以使用try-catch函数,寻找the standard deviation is zero这个错误,
  2. 如果the standard deviation is zero 发生此错误,函数应返回x 的平均值。
  3. 如果未找到错误,则返回cor(x,y) 输出。

预期没有错误消息,而是函数应该返回 x 值的平均值。

【问题讨论】:

    标签: r debugging error-handling dplyr try-catch


    【解决方案1】:

    您可以预先计算标准偏差,如果检查失败,则返回 x 的平均值。

    cor_fun<- function(x,y){
    
      if (any(sapply(list(x, y), FUN = sd) == 0)) {
        return(mean(x))
      } else {
        val <- cor(x,y)
        return(val)
      }
    }
    
    df %>%
      group_by(Tag) %>%
      summarise(c = cor_fun(x,y))
    
    # A tibble: 2 x 2
        Tag      c
      <dbl>  <dbl>
    1     1 -0.977
    2     2  1 
    

    如果你想走tryCatch路线,你可以这样做

    cor_fun<- function(x,y){
      val <- tryCatch(cor(x, y), error = function(e) e, warning = function(w) w)
      if (any(class(val) %in% c("simpleWarning", "warning"))) {
        return(mean(x))
      } else {
        return(val)
      }
    }
    

    tryCatch 计算一个表达式,在您的情况下为 cor(x, y)。如果表达式返回错误或警告,它将将该错误存储在val 中并继续下一行。如果表达式按预期计算,它将存储在val 中,就像什么也没发生一样。当发生错误或警告时,val 的类会从预期的变化,例如numericsimpleWarningsimpleError。我用它来捕捉表达式的评估是否失败并处理它。这种处理也可以在function(e) e 调用中完成。

    下面是处理 tryCatch 调用中的警告。

    cor_fun<- function(x,y){
      val <- tryCatch(cor(x, y), 
                      error = function(e) e,
                      warning = function(w) {
                        # in case there is a warning (for whatever reason)
                        # return mean of x
                        return(mean(x))
                      })
      val
    }
    

    您可以在?tryCatch 文档或例如here.

    【讨论】:

    • .!谢谢你的回复。你能解释一下tryCatch代码吗:
    • @Harvey 当然,请参阅我的评论。请注意,tryCatch 的文档并不是最糟糕的。您还可以通过其他在线资源来了解这一点。
    猜你喜欢
    • 2012-02-25
    • 1970-01-01
    • 2016-07-28
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 1970-01-01
    • 1970-01-01
    • 2017-04-08
    相关资源
    最近更新 更多