R/table_freq_cross.R

Defines functions table.freq.cross

Documented in table.freq.cross

#' Cette fonction permet de faire des tris à plats non-pondérés
#'
#' @param data Input data.frame
#' @param var Variable to cross
#' @param crossvar Cross variable
#' @param path Systeme path for save plots
#' @examples  
#'   lst = sapply(seq_along(dat), function(x) table.freq.cross(dat, x, crossvar, getwd()), simplify = F)
#' @export

# Fonction de tri à plat non-pondéré
table.freq.cross = function(data, var, crossvar){
   # Select columns
   dat = data %>% 
      select_(.dots = c(crossvar, var))
   
   # Tris
   lst = sapply(c(1:ncol(dat))[-1], function(x) {
       descr::crosstab(dat[[x]], dat[[1]], prop.c = TRUE, plot = FALSE, format = "SPSS")$prop.col
   }, simplify = F)
   
   # Test chi2
   lst_chi = sapply(c(1:ncol(dat))[-1], function(x) {
      tryCatch({
         tb = descr::crosstab(dat[[x]], dat[[1]], prop.c = TRUE, plot = FALSE, format = "SPSS", chisq = TRUE)$CST
         # Collect them
         res = tribble(
            ~"value", ~"p.value", 
            tb$statistic, tb$p.value
         )
      }, error = function(cond) return(NA))
   }, simplify = F) %>% 
      mapply(`[<-`, ., 'variable', value = c(1:ncol(dat))[-1], SIMPLIFY = FALSE) %>% 
      rbind_all() %>% 
      select(variable, value, p.value)
   
   # Merge 
   lst = cbind(lst[[1]],"Chi" = c(lst_chi[1,3], rep(NA, nrow(lst[[1]]))))
   
   # Output
   return(lst)
}
AlexisMayer/toolbox documentation built on Aug. 25, 2020, 3:56 p.m.