簡體   English   中英

R中分組數據的二次擬合

[英]Quadratic fitting for grouped data in R

盡管我在總體擬合模型方面找到了很多幫助,但是由於數據的組織方式,我一直遇到數據的特定問題。 它是從Intro Stats書中摘錄的,應該將誤差的樣本數據表示為某種葯物毫克數的函數。

|-----|-------|-------|-------|
| 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。一個階數為n的變量x的多項式擬合將擬合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")

您可以看到它是真實圖案的平滑版本(第一幅圖)。

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM