[R] Fisher test

Thomas Lumley tlumley at u.washington.edu
Thu May 30 17:29:46 CEST 2002

On Thu, 30 May 2002, Ambrosini Alessandro wrote:

> Hello! I started from two matrix. I made "margin.table" and so now I have
> two vectors. I have to take the first elements of the two vectors, and the
> sum of the remaining element of each vector.
> I make a example.Suppose to have (1,3,5,7,9)
>                                  (2,6,8,0,1)
> I want to take 1,2 that are the first elements of the vectors, and make
> 3+5+7+9=24 for the first vector and 6+8+0+1=15 for the second. At this point
> I build a table in this way
>    1  24
>    2  15
> For this table I use the Fisher exact test. After this I have to take the
> second elements of the vectors, find the sum of the rest of the vectors,
> build another table and make Fisher. I have to do it for all the elements of
> the vectors. In this case I have to find 5 tables. The problem is that I
> have vectors with 1000 elements.
> I know that I have to use "for" to build the table.
> I know also that everytime fisher.test gives me the reslut.

Suppose a and b are your two vectors.  You can do


and then
   pvalues<-sapply(1:999, function(i)
using the fact (which you can discover from the help or by using str())
that the p value is the $p.value component of the result of the test.

You could also construct a 2x2x999 array from a[-1000],b[-1000],A[-1] and
B[-1] and use apply() to do the tests to each layer
   pvalues<-apply(M,1,function(m) fisher.test(m)$p.value)

or use a for() loop explicitly, in which case you need to define the
vector first

for(i in 1:999){
   pvalues[i]<- fisher.test(matrix(c(a[i],b[i],A[i+1],B[i+1]),2))$p.values

I think the apply version is the neatest.  They all seem to have about the
same speed on the one example I tried.


r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch

More information about the R-help mailing list