Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am running a Fisher Exact test on some contingency matrix in R. However, using this code:

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"), "")
        }
    }
}

I am getting the following error:

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

As you can see, the matrix genemat is nonnegative and finite.

str(genemat) returns:

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

What am I doing wrong?

Thanks

like image 972
gc5 Avatar asked Mar 23 '15 15:03

gc5


1 Answers

You use matrix on a one-row data.frame, which results in a list with dimension attribute (i.e., a special kind of matrix). That's not what you intended. Use unlist to make the data.frame row an atomic vector first:

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
like image 93
Roland Avatar answered Nov 15 '22 06:11

Roland