首页 > 解决方案 > Shapiro.test 错误消息:尝试将属性设置为 NULL

问题描述

我正在尝试通过视觉和测试来测试某些股票收益的正常性。我想我的直方图是正确的,但是夏皮罗测试给了我以下错误信息:

.xts(e, .index(e2), .indexCLASS = indexClass(e2), .indexFORMAT = indexFormat(e2), 中的错误:尝试将属性设置为 NULL

我试图使以下代码可重现,但如果还有其他需要,请告诉我。

library(quantmod)

DNB = getSymbols("DNB.OL", src = 'yahoo', 
           from = "2020-01-01",
           to = "2020-12-31")

DNBclose <- DNB.OL$DNB.OL.Close
DNBreturn <- dailyReturn(DNBclose, type = "log", leading = "FALSE")

std <- sqrt(var(DNBreturn, na.rm = TRUE))
DNBmean <- mean(DNBreturn, na.rm = TRUE)

DNBhist <- hist(DNBreturn, density=20, breaks=20, prob=TRUE, 
     xlab="x-variable", ylim=c(0, 35), 
     main="normal curve over histogram")
 curve(dnorm(x, mean=DNBmean, sd=std), 
      col="darkblue", lwd=2, add=TRUE, yaxt="n")
 
shapiro.test(DNBreturn)

标签: r

解决方案


根据?shapiro.test,输入 'x'

x - 数据值的数值向量。允许缺失值,但非缺失值的数量必须在 3 到 5000 之间。

在这里,我们有一个“xts”对象,它基本上也继承了一个matrix类。因此,我们可以vector使用as.numeric或转换为as.vector

shapiro.test(as.numeric(DNBreturn))

    Shapiro-Wilk normality test

data:  as.numeric(DNBreturn)
W = 0.93466, p-value = 4.172e-09

matrix再次调用以删除xts

shapiro.test(matrix(DNBreturn))
Shapiro-Wilk normality test

data:  matrix(DNBreturn)
W = 0.93466, p-value = 4.172e-09

或者可以更改class分配

class(DNBreturn) <- "matrix"
shapiro.test(DNBreturn)

    Shapiro-Wilk normality test

data:  DNBreturn
W = 0.93466, p-value = 4.172e-09

推荐阅读