Thursday, January 26, 2017

Cochran-Mantel-Haenszel Simplified

# To use: 
# simple_mh(df1$your_exp,df1$your_out,df1$your_grp) 
# probably better if your exposure and outcome are coded 1 for yes and 0 for no - but then they should (probably) be anyway.
simple_mh <- function(exposure,outcome,grp){
    df1 <- data.frame(exposure,outcome,grp)
    s_df1 <- split(df1,df1$grp)
    f <- function(x){
        exposure <- x$exposure
        outcome <- x$outcome
        tab <- table(exposure,outcome)
        return(tab)
    }
    lst0 <- sapply(s_df1,f,simplify="array")
     print(mantelhaen.test(lst0))
}