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

问题描述 投票:2回答:1

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

  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:11列中的值。

我想获得两个函数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应用我的方式导致错误以及如何正确地做到这一点?

r
1个回答
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)
© www.soinside.com 2019 - 2024. All rights reserved.