原文連結:http://tecdat.cn/?p=9484
原文出處:拓端資料部落公衆号
目錄
怎麼做測試
功率分析
介紹
下面以物種多樣性為例子展示了如何在R語言中進行相關分析和線性回歸分析。
怎麼做測試
相關和線性回歸示例
Data = read.table(textConnection(Input),header=TRUE)
資料簡單圖
plot(Species ~ Latitude,
data=Data,
pch=16,
xlab = "Latitude",
ylab = "Species")
相關性
可以使用 cor.test函數。它可以執行Pearson,Kendall和Spearman相關。
皮爾遜相關
皮爾遜相關是最常見的相關形式。假設資料是線性相關的,并且殘差呈正态分布。
cor.test( ~ Species + Latitude,
data=Data,
method = "pearson",
conf.level = 0.95)
Pearson's product-moment correlation
t = -2.0225, df = 15, p-value = 0.06134
cor
-0.4628844
肯德爾相關
肯德爾秩相關是一種非參數檢驗,它不假設資料的分布或資料是線性相關的。它對資料進行排名以确定相關程度。
cor.test( ~ Species + Latitude,
data=Data,
method = "kendall",
continuity = FALSE,
conf.level = 0.95)
Kendall's rank correlation tau
z = -1.3234, p-value = 0.1857
tau
-0.2388326
斯皮爾曼相關
Spearman等級相關性是一種非參數檢驗,它不假設資料的分布或資料是線性相關的。它對資料進行排序以确定相關程度,并且适合于順序測量。
線性回歸
線性回歸可以使用 lm函數執行。可以使用lmrob函數執行穩健回歸。
summary(model) # shows parameter estimates,
# p-value for model, r-square
Estimate Std. Error t value Pr(>|t|)
(Intercept) 585.145 230.024 2.544 0.0225 *
Latitude -12.039 5.953 -2.022 0.0613 .
Multiple R-squared: 0.2143, Adjusted R-squared: 0.1619
F-statistic: 4.09 on 1 and 15 DF, p-value: 0.06134
Response: Species
Sum Sq Df F value Pr(>F)
Latitude 1096.6 1 4.0903 0.06134 .
Residuals 4021.4 15
繪制線性回歸
plot(Species ~ Latitude,
data = Data,
pch=16,
xlab = "Latitude",
ylab = "Species")
abline(int, slope,
lty=1, lwd=2, col="blue") # style and color of line
檢查模型的假設
線性模型中殘差的直方圖。這些殘差的分布應近似正态。
殘差與預測值的關系圖。殘差應無偏且均等。
穩健回歸
該線性回歸對響應變量中的異常值不敏感。
summary(model) # shows parameter estimates, r-square
Estimate Std. Error t value Pr(>|t|)
(Intercept) 568.830 230.203 2.471 0.0259 *
Latitude -11.619 5.912 -1.966 0.0681 .
Multiple R-squared: 0.1846, Adjusted R-squared: 0.1302
anova(model, model.null) # shows p-value for model
pseudoDf Test.Stat Df Pr(>chisq)
1 15
2 16 3.8634 1 0.04935 *
繪制模型
線性回歸示例
summary(model) # shows parameter estimates,
# p-value for model, r-square
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 12.6890 4.2009 3.021 0.0056 **
Weight 1.6017 0.6176 2.593 0.0154 *
Multiple R-squared: 0.2055, Adjusted R-squared: 0.175
F-statistic: 6.726 on 1 and 26 DF, p-value: 0.0154
### Neither the r-squared nor the p-value agrees with what is reported
### in the Handbook.
library(car)
Anova(model, type="II") # shows p-value for effects in model
Sum Sq Df F value Pr(>F)
Weight 93.89 1 6.7258 0.0154 *
Residuals 362.96 26
# # #
功率分析
功率分析的相關性
### --------------------------------------------------------------
### Power analysis, correlation
### --------------------------------------------------------------
pwr.r.test()
approximate correlation power calculation (arctangh transformation)
n = 28.87376