1. 程式人生 > 其它 >R-正態性檢驗例項

R-正態性檢驗例項

資料:price.csv檔案(一列價格差值的資料,包含標題)

問題描述:

  • 利用price.csv資料繪製資料直方圖,並新增概率密度曲線(density)和估計概率密度曲線(dnorm) 。
  • 繪製出qqplot及其擬合線。
  • 用Shapiro和Kolmogorov-Smirnov檢驗判斷該資料是否符合正態分佈。

程式碼實現:

data = read.csv("price.csv", header = T)
hist(data$diff, freq = F, xlab = 'Price differences', ylab = 'Density')  #繪製直方圖
lines(density(data$diff), col = 'black')  #新增概率密度曲線
x = seq(-2, 2, len = 252)
lines(x, dnorm(x, mean(data$diff), sd(data$diff)), col= 'blue')  #新增估計概率密度曲線

qqnorm(data$diff)  #繪製qqplot
qqline(data$diff)  #繪製擬合線

shapiro.test(data$diff)

ks.test(data$diff, 'pnorm', mean = mean(data$diff), sd = sd(data$diff))

  

結果展示:

> shapiro.test(data$diff)

	Shapiro-Wilk normality test

data:  data$diff
W = 0.99146, p-value = 0.1503

> ks.test(data$diff, 'pnorm', mean = mean(data$diff), sd = sd(data$diff))

	One-sample Kolmogorov-Smirnov test

data:  data$diff
D = 0.052668, p-value = 0.4867
alternative hypothesis: two-sided

  兩種檢驗均表明該資料服從正態分佈。