Skip to content

Instantly share code, notes, and snippets.

@dceoy
Last active June 6, 2021 02:05
Show Gist options
  • Save dceoy/4d75564e5f44702ee3bc to your computer and use it in GitHub Desktop.
Save dceoy/4d75564e5f44702ee3bc to your computer and use it in GitHub Desktop.
[R] Fisher's Exact Test on each row of a data frame
#!/usr/bin/env Rscript
# fisher test on each row
row_fisher <- function(row, alt = 'two.sided', cnf = 0.95) {
f <- fisher.test(matrix(row, nrow = 2), alternative = alt, conf.level = cnf)
return(c(row,
p_val = f$p.value,
or = f$estimate[[1]],
or_ll = f$conf.int[1],
or_ul = f$conf.int[2]))
}
# generate sample data for test
test_df <- data.frame(matrix(sample.int(1000, size = 4000, replace = TRUE), ncol = 4))
colnames(test_df) <- c('a', 'b', 'c', 'd')
# run
p <- data.frame(t(apply(test_df, 1, row_fisher)))
print(p)
#!/usr/bin/env Rscript
#
# outcome
# + -
# +-------+-------+
# + | a | b | a + b
# group +-------+-------+
# - | c | d | c + d
# +-------+-------+
# a + c b + d
#
sapply(c('dplyr', 'snow'), function(p) require(p, character.only = TRUE))
cl <- makeCluster(parallel::detectCores(), type = 'SOCK')
# fisher test on each row
row_fisher <- function(row, alt = 'two.sided', cnf = 0.95) {
f <- fisher.test(matrix(row, nrow = 2), alternative = alt, conf.level = cnf)
return(c(row,
p_val = f$p.value,
or = f$estimate[[1]],
or_ll = f$conf.int[1],
or_ul = f$conf.int[2]))
}
# generate sample data for test
df_test <- tbl_df(matrix(sample.int(1000, size = 4000, replace = TRUE), ncol = 4)) %>%
rename(a = V1, b = V2, c = V3, d = V4)
# run
p <- df_test %>%
parApply(cl, ., 1, row_fisher) %>%
t() %>%
tbl_df()
print(p)
@XRCHAM
Copy link

XRCHAM commented Jul 31, 2019

Hi Daichi,
Excited to read your R script for doing fisher test for dataframe. I am new to R, and wonder what is the difference between the two "row_fisher_dt.R" scripts you showed here. And another thing is what is the meaning of "sample.int(1000, size = 4000, replace = TRUE)", should I replace it with my table?

Thanks,
Xiangbin

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment