0

在这里使用 Greg 的有用答案,我将二阶多项式回归线拟合到我的数据集:

poly.fit<-lm(y~poly(x,2),df)

当我绘制这条线时,我得到下图:

我的拟合线绘制。

系数是:

# Coefficients:
#   (Intercept)     poly(x, 2)1     poly(x, 2)2  
#         727.1           362.4          -269.0

然后我想找到峰值的 x 值。我认为在 R 中有一种简单的方法可以做到这一点,但我不知道,*所以我去了 Wolfram Alpha。我输入了等式:

y=727.1+362.4x-269x^2

Wolfram Alpha 返回以下内容:

如您所见,该函数在 x=2.4 处与 x 轴相交。这与我在 R 中的情节明显不同,范围为 0≤x≤80。为什么这些不同?R 是否将我的 x 值解释为某些后台变量的一部分?

*我也很感激如何找到这个峰值的答案。显然我可以取导数,但我如何设置为零?

4

2 回答 2

3

使用predict.

 plot( 40:90, predict( poly.fit, list(x=40:90) )
于 2015-06-14T22:11:29.597 回答
1

在二次多项式的情况下,您当然可以使用一些微积分和代数(一旦您有友好的系数)。

更一般地说,您可以通过在一系列候选值上评估您的模型并确定哪个为您提供最大响应值来获得估计值。

这是一个(仅适度鲁棒的)功能,可以在这里工作。

xmax <- function(fit, startx, endx, x='x', within=NA){
    ## find approximate value of variable x where model 
    ## specified by fit takes maximum value, inside interval 
    ## [startx, endx]; precision specified by within

    within <- ifelse(is.na(within), (endx - startx)/100, within)
    testx <- seq(startx, endx, by=within)
    testlist <- list(testx)
    names(testlist)[1] <- x
    testy <- predict(fit, testlist)
    testx[which.max(testy)]
}

请注意,如果您的预测变量被称为 x 以外的名称,您必须在x参数中将其指定为字符串。

因此,要找到曲线达到峰值的 x 值:

xmax(poly.fit, 50, 80, within=0.1)
于 2015-06-15T00:05:13.050 回答