R中分组数据的二次拟合

Quadratic fitting for grouped data in R

虽然我发现了很多关于拟合模型的一般帮助,但由于数据的组织方式,我将 运行 放在数据的特定问题上。它来自一本介绍统计书,应该表示错误的样本数据作为某种药物的毫克数的函数。

|-----|-------|-------|-------|
| 0mg | 100mg | 200mg | 300mg |
|-----|-------|-------|-------|
| 25  |  16   |   6   |   8   |
| 19  |  15   |  14   |  18   |
| 22  |  19   |   9   |   9   |
| 15  |  11   |   5   |  10   |
| 16  |  14   |   9   |  12   |
| 20  |  23   |  11   |  13   |

数据看起来像是围绕 C 组下降,然后 D 组上升一点,因此寻找二次拟合。

我尝试了以下方法:

scores = c(25, 19, 22, 15, 16, 20,
           16, 15, 19, 11, 14, 23,
            6, 14,  9,  5,  9, 11,
            8, 18,  9, 10, 12, 13)

x_groups = rep(c(0,100, 200, 300), each = 6)
scores.quadratic = lm(scores ~ poly(x_groups, 2, raw = TRUE))

然后我可以使用 summary() 函数来查看结果。我对 lm() 函数以及它应该如何拟合二次函数感到困惑。我的理解是,它将采用 x_groups 中的每个索引并对其进行平方,然后使用该新向量的线性拟合,但这对我来说似乎不正确。

有人可以就这应该如何拟合我的数据的二次方提供反馈,或者如果它没有这样做,请帮助我了解我哪里出错了。

谢谢。

让我们逐步了解您的思维方式。首先,您可以通过 C 组的数据发现这种下降。形象化的最佳方式是

library(ggplot2)
library(dplyr)

scores = c(25, 19, 22, 15, 16, 20,
           16, 15, 19, 11, 14, 23,
           6, 14,  9,  5,  9, 11,
           8, 18,  9, 10, 12, 13)

x_groups = rep(c(0,100, 200, 300), each = 6)

# create dataset
d1 = data.frame(scores, x_groups) 

# calcuate average scores for each group
d2 = d1 %>% group_by(x_groups) %>% summarise(Avg = mean(scores))

# plot them
ggplot() + 
  geom_point(data = d1, aes(x_groups, scores)) +
  geom_line(data = d2, aes(x_groups, Avg), col="blue")

现在您可以真正看到下降,这就是您想要建模的模式。

然后,您想要拟合您的二次模型。请记住,二次是多项式公式的一个特例,但它的阶数 = 2。变量 x 的阶数 = n 的多项式拟合将拟合 intercept + x + x^2 + x^3 + ... + x^n。因此,二次方程将拟合 intercept + x + x^2,这正是您在模型输出中获得的系数:

scores.quadratic = lm(scores ~ poly(x_groups, 2, raw = TRUE))
summary(scores.quadratic)

# Call:
#   lm(formula = scores ~ poly(x_groups, 2, raw = TRUE))
# 
# Residuals:
#   Min      1Q  Median      3Q     Max 
# -6.1250 -2.3333 -0.2083  1.8542  8.7917 
# 
# Coefficients:
#                                    Estimate Std. Error t value Pr(>|t|)    
#   (Intercept)                    20.2083333  1.5925328  12.689 2.58e-11 ***
#   poly(x_groups, 2, raw = TRUE)1 -0.0745833  0.0255747  -2.916  0.00825 ** 
#   poly(x_groups, 2, raw = TRUE)2  0.0001458  0.0000817   1.785  0.08870 .  
# ---
#   Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
# 
# Residual standard error: 4.002 on 21 degrees of freedom
# Multiple R-squared:  0.4999,  Adjusted R-squared:  0.4523 
# F-statistic:  10.5 on 2 and 21 DF,  p-value: 0.0006919

二次项的系数为 0.0001458 ,接近于零,但在 0.1 水平上显着不同于零(p 值 = 0.08870)。因此,模型有点感觉有下降。

您可以像这样绘制拟合:

# plot the model
ggplot(d1, aes(x_groups, scores)) + 
  geom_point() +
  geom_smooth(formula = y ~ poly(x, 2, raw = TRUE),
              method = "lm")

您可以将其视为真实模式(第一个图)的平滑版本。