R - 使用带有shapiro.test()的数字矩阵应用给出错误:所有'x'值都相同

时间:2016-01-17 16:23:21

标签: r

我有一个带有>的data.frame df 110 000行。它看起来像是:

  traking_id         A1_CTRL     A2_CTRL     A3_CTRL     A4_CTRL     A5_CTRL     A1_DEX      A2_DEX      A3_DEX      A4_DEX      A5_DEX
1 ENSMUST00000000001 1.35358e+01 1.03390e+01 1.03016e+01 1.12654e+01 1.22707e+01 1.40684e+01 9.15279e+00 1.17276e+01 1.14550e+01 1.46256e+01
2 ENSMUST00000000003 5.01868e-06 5.59107e-06 1.60922e-01 2.45402e-01 2.18614e-01 2.24124e-01 2.88035e-01 7.18876e-06 1.74746e-06 0.00000e+00
...

我有兴趣为每一行执行两次 shapiro.test - 一次是第2列中的值:6,第7列中的值是一次。

我想获得两个函数shapiro.test返回的对象列表,以便从中提取p.value列。我想通过使用函数apply来实现它,但是我的代码

shapiro.test_CTRL <- apply(data.matrix(df[,2:6]), 1, shapiro.test)

返回错误

Error in FUN(newX[, i], ...) : all 'x' values are identical

但是,当我使用pearson.test时,一切正常:

pearson.test_CTRL <- apply(data.matrix(df[,2:6]), 1, pearson.test)

仅为一行计算shapiro.test也可以正常工作:

shapiro.test(data.matrix(x[1,2:6]))

我想知道为什么使用shapiro.test应用我的方式会导致错误以及如何正确地执行此操作?

1 个答案:

答案 0 :(得分:2)

如果您查看shapiro.test的来源,则会显示以下内容:

...
        x <- sort(x[complete.cases(x)])
        n <- length(x)
        if (is.na(n) || n < 3L || n > 5000L) 
            stop("sample size must be between 3 and 5000")
        rng <- x[n] - x[1L]
        if (rng == 0) 
            stop("all 'x' values are identical")
...

触发此错误,您的行的值都相同。使用此代码可以触发相同的错误:

mtcars[2,] <- 1
apply(mtcars[,2:5], 1, shapiro.test)

您可以通过测试该条件并返回其他内容来避免此错误:

f <- function(x) {
  if (diff(range(x)) == 0) list() else shapiro.test(x)
}

apply(mtcars[,2:5], 1, f)