簡體   English   中英

在group_by中調用cor函數時,“標准偏差為零”錯誤

[英]`The standard deviation is zero` error with cor function calling in group_by

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))

在這里,我們試圖計算之間的相關性xy通過group_by (TAG)。問題是,當我們計算用於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值的均值。

您可以預先計算標准偏差,如果未通過檢查,則返回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的類別將從預期的值(例如, numeric更改為simpleWarningsimpleError 我用它來捕獲表達式的評估是否失敗並進行處理。 此處理也可以在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文檔或此處閱讀更多內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM