R中的正态性测试程序

时间:2015-02-12 15:01:20

标签: r distribution skew

有人可以帮忙在我的代码中找到错误吗? 我想在R中制作一个程序,告诉我分发是否正常。它还应该打印带有密度曲线的直方图。 在阅读.csv文件和所需的包(moments and ggplot2)之后,我使用shapiro wilks test(normality <- shapiro.test())测试我的数据是否正常。在测试之后,获得p值以在if函数(normality$p.value<0.05)中使用。

if函数应该有点像这样:

如果p值小于0.05,则测试偏斜度。如果偏度小于-0,5,则分布向右移动并打印出它的直方图。如果偏斜度高于> 0.5,则分布向左移动,打印直方图。如果偏斜在0.5和-0.5之间,则分布是近似拟合的。 另外,分布是正常的。

运行我的代码后,没有任何反应。有人建议可能出错吗?有没有人有更好的解决方案?

library("moments")
library("ggplot2")


histogram <- qplot(data,  binwidth = 1.0, geom = "histogram", xlab = "my data", 
                   ylab = "data frequency", 
                   y = ..density.., fill = I("salmon"), colour = I("black")) +
  stat_density(geom = "line")

normality <- shapiro.test(data)
skew <- skewness(data)



if(normality$p.value<0.05){
    if(skew< -0.5){
    "The distribution is shifted into the right"
    histogram
    return()
  }
  if(skew> 0.5){
    "The distribution is shifted into the left"
    histogram;
    return()
  }
  if(skew<=0.5 && skew>=-0.5){
    "The distribution is simetrical"
    return()
  }
  else{
    "The distribution is normal"
    histogram
  }
}

编辑: 除了之前的代码,我尝试采用不同的方法,但仍然无法正常工作。如果有人会说出我做错了什么,我会非常感激:

result <- shapiro.test(dat)
skew <- skewness(dat)

if(result$p.value>0.05)
{
   "The distribution is normal"
    print(histogram)
    } else if(result$p.value<0.05 && skew < (-0.5))
      {
       display <- sprintf("The curve is shifted to the right, skewness = %f", skew)
       print(display)     
       print (histogram)
    }else (result$p.value<0.05 && skew> 0.5)
     {
       display<- sprintf("The curve is shifted to the left, skewness = %f", skew)
       print(histogram)
       print(display)
    }

0 个答案:

没有答案