问题
I have a data frame of n rows that resembles below (with some extra columns containing additional information not listed):
R1counti R1counto R2counti R2counto R1 R2
sample1 100 100 1000 1000 1 1
smaple2 50 100 50 50 0.5 1
For each row, I want to perform a fisher's exact test to determine if the R1 ratio is significantly different from the R2 ratios (and also in the end get an adjusted p-val)
Desired output (with the count columns still included in the out):
R1 R2 pval
sample1 1 1 1
sample2 0.5 1 0.05
I thought I could do something like:
dataframe$p-val <- with(dataframe, p-val <- fisher.test(R1, R2, alternative= "two.sided"))
But I get an error:
FEXACT error 40.
Out of workspace.
Maybe I'm not handling this situation correctly. Any advice? Suggestions? Can I perform a fishers test like this?
回答1:
For each row of your dataset you need to build a matrix (i.e. a 2 x 2 contingency table) and pass this matrix to the fisher.test
command.
df <- read.table(text="
R1counti R1counto R2counti R2counto R1 R2
sample1 100 100 1000 1000 1 1
sample2 50 100 50 50 0.5 1
", header=T, row.names=1)
apply(df, 1,
function(x) {
tbl <- matrix(as.numeric(x[1:4]), ncol=2, byrow=T)
fisher.test(tbl, alternative="two.sided")$p.value
})
# sample1 sample2
# 1.00000000 0.01209383
来源:https://stackoverflow.com/questions/52784396/fishers-exact-test-on-rows-in-data-frame-r