Error: all entries of 'x' must be nonnegative and finite in fisher.test

Error: all entries of 'x' must be nonnegative and finite in fisher.test

我是 运行 对 R 中某些列联矩阵的 Fisher 精确检验。但是,使用此代码:

for (class in 1:5) {
    for (test in c("amp", "del")) {
        prefisher <- read.table("prefisher.txt", sep="\t", row.names=1)
        for (gene in rownames(prefisher)) {
            genemat <- matrix(prefisher[gene,], ncol=2)
            print(genemat)
            result <- fisher.test(genemat)
            write(paste(gene, result$estimate, result$p.value, sep = "\t"), "")
        }
    }
}

我收到以下错误:

    [,1] [,2]
[1,] 1    0   
[2,] 101  287 
Error in fisher.test(genemat): all entries of 'x' must be nonnegative and finite

如您所见,矩阵 genemat 是非负且有限的。

str(genemat) returns:

List of 4
 $ : int 1
 $ : int 101
 $ : int 0
 $ : int 287
  - attr(*, "dim")= int [1:2] 2 2

我做错了什么?

谢谢

您在单行 data.frame 上使用 matrix,这会生成具有维度属性的列表(即,一种特殊的矩阵)。那不是你想要的。首先使用 unlist 使 data.frame 行成为原子向量:

DF <- data.frame(a = 1, b = 101, c = 0, d = 287)
m <- matrix(DF, 2)
str(m)
# List of 4
#  $ : num 1
#  $ : num 101
#  $ : num 0
#  $ : num 287
# - attr(*, "dim")= int [1:2] 2 2

fisher.test(m)
#Error in fisher.test(m) : 
#  all entries of 'x' must be nonnegative and finite

m <- matrix(unlist(DF), 2)
fisher.test(m)
#no error