gpt4 book ai didi

r - 在group_by中调用cor函数的`The standard deviation is zero`错误

转载 作者:行者123 更新时间:2023-12-03 07:46:34 25 4
gpt4 key购买 nike

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

在这里我们试图通过 x(Tag)计算 ygroup_by之间的相关性。问题是当我们计算x&y和的相关性时,任何一列的标准差为0,会吐出误差为 the standard deviation is zero在生产中 Not Acceptable 。因此,除了 the standard deviation is zero发生时,我的功能是返回x的均值,否则应返回相关输出。我尝试重现粘贴在下面的相同场景,请对此进行指导。
在函数名称 cor_fun中使用try-catch 来使用

简要要求
  • 内部函数,我们可以使用try-catch函数并查找the standard deviation is zero此错误
  • 如果the standard deviation is zero发生此错误,函数应返回x的均值。
  • 如果未发现错误,则返回cor(x,y)输出。

  • Here the screen shot of error message

    预期没有错误消息,而是函数应返回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的类别与预期的有所不同,例如 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

    关于r - 在group_by中调用cor函数的`The standard deviation is zero`错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51682643/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com