我怎样才能获得rsquare出ANOVA在R中
答
TL;博士:你可以得到的R平方通过查看相应的线性模型的总结输出的方差分析
让我们走一步看一步:
1)让我们用数据来自here
pain <- c(4, 5, 4, 3, 2, 4, 3, 4, 4, 6, 8, 4, 5, 4, 6, 5, 8, 6, 6, 7, 6, 6, 7, 5, 6, 5, 5)
drug <- c(rep("A", 9), rep("B", 9), rep("C", 9))
migraine <- data.frame(pain, drug)
2)让我们方差分析:
AOV <- aov(pain ~ drug, data=migraine)
summary(AOV)
## Df Sum Sq Mean Sq F value Pr(>F)
## drug 2 28.22 14.111 11.91 0.000256 ***
## Residuals 24 28.44 1.185
## ---
## Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
3)现在,方差分析,直接关系到线性模型,让我们得到它,并从中找到ANOVA:
LM <- lm(pain ~ drug, data=migraine)
anova(LM)
## Analysis of Variance Table
##
## Response: pain
## Df Sum Sq Mean Sq F value Pr(>F)
## drug 2 28.222 14.1111 11.906 0.0002559 ***
## Residuals 24 28.444 1.1852
## ---
## Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
正如预期的那样,结果是完全一样的。这意味着...
3)我们可以得到的R平方从线性模型:
summary(LM)
## Call:
## lm(formula = pain ~ drug, data = migraine)
##
## Residuals:
## Min 1Q Median 3Q Max
## -1.7778 -0.7778 0.1111 0.3333 2.2222
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 3.6667 0.3629 10.104 4.01e-10 ***
## drugB 2.1111 0.5132 4.114 0.000395 ***
## drugC 2.2222 0.5132 4.330 0.000228 ***
## ---
## Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
##
## Residual standard error: 1.089 on 24 degrees of freedom
## Multiple R-squared: 0.498, Adjusted R-squared: 0.4562
## F-statistic: 11.91 on 2 and 24 DF, p-value: 0.0002559
因此,R平方为0.498
但是,如果我们不什么”你相信吗?
4)什么是R平方?它是平方和回归除以总平方和(即,回归平方和加上残差平方和)。因此,让我们找到了方差分析这些数字,并计算R平方直接:
# We use the tidy function from the broom package to extract values
library(broom)
tidy_aov <- tidy(AOV)
tidy_aov
## term df sumsq meansq statistic p.value
## 1 drug 2 28.22222 14.111111 11.90625 0.0002558807
## 2 Residuals 24 28.44444 1.185185 NA NA
# The values we need are in the sumsq column of this data frame
sum_squares_regression <- tidy_aov$sumsq[1]
sum_squares_residuals <- tidy_aov$sumsq[2]
R_squared <- sum_squares_regression/
(sum_squares_regression + sum_squares_residuals)
R_squared
## 0.4980392
所以我们得到相同的结果:R平方为0.4980392
谢谢大家,它现在很清楚了! – jakzr