gpt4 book ai didi

r - 如何处理完美拟合线性模型

转载 作者:行者123 更新时间:2023-12-02 04:25:13 24 4
gpt4 key购买 nike

我正在处理的数据偶尔有一个“完美拟合”的线性模型。对于我运行的每个回归,我需要提取我一直在使用 summary(mymodel)$r.squared 执行的 r.squared 值,但这在完美拟合模型的情况下会失败(请参阅如下)。

df <- data.frame(x = c(1,2,3,4,5), y = c(1,1,1,1,1))
mymodel <- lm(y ~ x, data = df)
summary(mymodel)$r.squared #This raises a warning
0.5294

我该如何处理这些情况?基本上,我想我想做类似的事情

If(mymodel is a perfect fit)
rsquared = 1
else
rsquared = summary(mymodel)$r.squared

最佳答案

您可以使用tryCatch

df <- data.frame(x = c(1,2,3,4,5), y = c(1,1,1,1,1))
mymodel <- lm(y ~ x, data = df)
summary(mymodel)$r.squared #This raises a warning

tryCatch(summary(mymodel)$r.squared, warning = function(w) return(1))
# [1] 1

并添加条件来捕获特定警告

df <- data.frame(x = c(1,2,3,4,5), y = c(1,1,1,1,1))
mymodel <- lm(y ~ x, data = df)
summary(mymodel)$r.squared #This raises a warning

f <- function(expr) {
tryCatch(expr,
warning = function(w) {
if (grepl('perfect fit', w))
return(1)
else return(w)
})
}

f(TRUE)
# [1] TRUE

f(sum(1:5))
# [1] 15

f(summary(mymodel)$r.squared)
# [1] 1

f(warning('this is not a fit warning'))
# <simpleWarning in doTryCatch(return(expr), name, parentenv, handler): this is not a fit warning>

关于r - 如何处理完美拟合线性模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27569941/

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