R/misc.R

Defines functions get_statistic tableone_list2df

tableone_list2df  <- function(table_one, non_normal=NULL,
                              two_level=NULL,...){
    res <- print(
        table_one,
        nonnormal = non_normal,# nonparametric test
        #exact = c("status", "stage"), # fisher.test
        cramVars = two_level, # both levels are shown
        #dropEqual = TRUE,
        showAllLevels = TRUE,
        quote = FALSE
    )

    #==== edit results
    colnames(res) <-  stringr::str_replace_all(colnames(res), '"', '')
    res <-
        res %>%
        as.data.frame() %>%
        mutate(Variable = stringr::str_replace_all(rownames(res), '"', '')) %>%
        select(Variable, everything())
    return(res)
}



get_statistic <- function(v, type, df) {
    var <- pull(df, !!treat_input_as_expr(v) )

    group <- pull(df, "group")


    if (type == "(mean (sd))"){
        t <- t.test(var ~ group)$statistic  %>% round(digits = 3) %>%
            paste0("t = ", .)
        return(t)
    }
    if (type == "(median [IQR])"){
        w <- wilcox.test(var ~ group)$statistic %>% round(digits = 3) %>%
            paste0("W = ", .)
        return(w)
    }
    if (type == "(%)"){
        x <- chisq.test(table(var, group))$statistic %>% round(digits = 3) %>%
            paste0("X-squared = ", .)
        return(x)
    }
}
jixing475/manuscriptsJX documentation built on April 20, 2020, 9:55 a.m.