【发布时间】:2018-01-24 00:29:43
【问题描述】:
我有一个函数尝试将分段回归模型应用于我的数据。 在某些情况下,数据有大量缺失值,我无法很好地估计结点的位置。我决定绕过分段并进行简单的线性回归:
try(piecewise) if error go to lm with just one slope
这是执行此操作的代码。请注意,lin.reg 是一个辅助函数,它为 x 范围内的 lm 对象输出 predict()。它不会产生任何问题。
piece <- function(x,y){
# just in case this comes with column names or something
y <- as.numeric(y)
# create the lm object
lm.obj <- lm(y~x)
# Try to fit piecewise
seg <- try(segmented(lm.obj,seg.Z=~x))
# print(seg)
if("try-error" %in% class(seg)) {
# Print that you are using a linear regression and not the piece-wise
print("Using linear Regression")
# Call helper function
result <- lin.reg(x,y)
# Get out of the error/function
return(result)
}
# Use the piece-wise
result <- predict(segmented::segmented(lm.obj,seg.Z=~x),
newdata = data.frame(x,y))
print("Using piece-wise regression")
return(result)
}
问题
分段出错时出现此错误
错误:至少一个系数为 NA:边界处的断点? (可能复制了许多 x 值)
但是它是不可靠/不可预测的,有时它会被忽略,有时它会破坏功能。我正在使用 y 值循环数据帧的行,并且在制动之前,相同的调用会到达不同的行。
我相信这与if("try-error" %in% class(seg)) 可能不是捕捉错误的最佳方法有关。
我添加了一些打印以确保。这是它正常工作的时候,注意迭代 284 给出了错误并转到了简单的线性。
[1] "Using piece-wise regression"
[1] 283
[1] "segmented" "lm"
[1] "Using piece-wise regression"
[1] 284
Error : at least one coef is NA: breakpoint(s) at the boundary? (possibly with many x-values replicated)
[1] "try-error"
[1] "Using linear Regression"
当它没有的时候,好像 try() 调用没有返回它应该返回的错误
[1] "Using piece-wise regression"
[1] 312
[1] "segmented" "lm"
[1] "Using piece-wise regression"
[1] 313
[1] "segmented" "lm"
Error: at least one coef is NA: breakpoint(s) at the boundary? (possibly with many x-values replicated)
【问题讨论】:
-
这对你来说可能很有趣:stackoverflow.com/questions/12135400/…
标签: r error-handling try-catch linear-regression