With the data.frame below,
# convert to data matrix
myMat <- data.matrix(df[-1])
# add rownames to matrix
rownames(myMat) <- df[[1]]
# run the test, store results in a list
myTests <- lapply(seq_len(nrow(myMat)), function(i) fisher.test(matrix(myMat[i,], nrow=2)))
Now, check out some of the results.
myTests[[1]]
Fisher's Exact Test for Count Data
data: matrix(myMat[i, ], nrow = 2)
p-value = 0.2224
alternative hypothesis: true odds ratio is not equal to 1
95 percent confidence interval:
0.3964215 1.2342274
sample estimates:
odds ratio
0.7006909
Take a look at what the test stores:
str(myTests[[1]])
List of 7
$ p.value : num 0.222
$ conf.int : atomic [1:2] 0.396 1.234
..- attr(*, "conf.level")= num 0.95
$ estimate : Named num 0.701
..- attr(*, "names")= chr "odds ratio"
$ null.value : Named num 1
..- attr(*, "names")= chr "odds ratio"
$ alternative: chr "two.sided"
$ method : chr "Fisher's Exact Test for Count Data"
$ data.name : chr "matrix(myMat[i, ], nrow = 2)"
- attr(*, "class")= chr "htest"
Pull out an interesting part of the test, the p-value
myTests[[1]]$p.value
[1] 0.2223973
Now, pull out the p-values from all of the tests
unlist(lapply(myTests, function(i) i$p.value))
[1] 0.22239730 0.01993561 0.87802037 0.10923094 0.33248291 0.08389711
This should get you started. I'd recommend looking up each of the unfamiliar functions in the help files and reading gregor's answer on this post on working with lists and why that is the way to go in R.
data
df <- structure(list(V1 = structure(1:6, .Label = c("aa", "bb", "cc",
"dd", "ee", "ff"), class = "factor"), V2 = c(58L, 65L, 35L, 36L,
27L, 30L), V3 = c(76L, 69L, 99L, 98L, 107L, 104L), V4 = c(48L,
30L, 23L, 16L, 24L, 12L), V5 = c(44L, 62L, 69L, 76L, 68L, 80L
)), .Names = c("V1", "V2", "V3", "V4", "V5"), class = "data.frame", row.names = c(NA,
-6L))