R/math.chi-squared.R

Defines functions fisher_test chi_test

#' @export
chi_test <- function(x,y,
                     x.name=feR:::.var.name(deparse(substitute(x))),
                     y.name = feR:::.var.name(deparse(substitute(y))),
                     p.sig=0.05,
                     stop.on.error = FALSE,
                     lang = "es",
                     digits = 4,
                     DEBUG = FALSE
                    ){

  if (missing(x)) {
    msg <- feR:::.error.msg("MISSING_X", lang = lang)
    if (stop.on.error) stop(msg)
    else message(msg)
  }

  if (missing(y))  {
    msg <- feR:::.error.msg("MISSING_BY", lang = lang)
    if (stop.on.error) stop(msg)
    else message(msg)
  }

  result.temp = chisq.test(x,y)


  result <- data.frame(
              test.name = "Pearson's",
              stat.name = "chiĀ² Pearson",
              stat.value = ifelse(is.numeric(result.temp$statistic),round(result.temp$statistic,digits = digits),result.temp$statistic),
              df = result.temp$parameter,
              p.value = round(result.temp$p.value, digits = (digits + 1))
  )
  attr(result,"OBSERVED") <- result.temp$observed
  attr(result, "EXPECTED") <- result.temp$expected

  class(result) <- c("feR.comp_prop",class(result))
  result
}


#' @export
fisher_test <- function(x,y,
                     x.name=feR:::.var.name(deparse(substitute(x))),
                     y.name = feR:::.var.name(deparse(substitute(y))),
                     p.sig=0.05,
                     stop.on.error = FALSE,
                     lang = "es",
                     digits = 4,
                     DEBUG = FALSE
){

  if (missing(x)) {
    msg <- feR:::.error.msg("MISSING_X", lang = lang)
    if (stop.on.error) stop(msg)
    else message(msg)
  }

  if (missing(y))  {
    msg <- feR:::.error.msg("MISSING_BY", lang = lang)
    if (stop.on.error) stop(msg)
    else message(msg)
  }

  result.temp = fisher.test(x,y)

  if("estimate" %in% names(result.temp)) {
    if(is.numeric(result.temp$estimate)) stat.val = round(result.temp$estimate, digits = digits)
    else stat.val = result.temp$estimate
  } else stat.val <- NA

  if("conf.int" %in% names(result.temp)) {
    if(is.numeric(result.temp$result.temp$conf.int[1])) conf.hi = round(result.temp$result.temp$conf.int[1], digits = digits)
    else conf.hi = result.temp$conf.int[1]
    if(is.numeric(result.temp$result.temp$conf.int[2])) conf.low = round(result.temp$result.temp$conf.int[2], digits = digits)
    else conf.low = result.temp$conf.int[2]
  } else {
    conf.hi <- NA
    conf.low <- NA
  }



  result <- data.frame(
    test.name = "Fisher's",
    stat.name = "odds ratio",
    stat.value = stat.val,
    stat.value.ci.low = conf.low,
    stat.value.ci.high = conf.hi,
    # df = result.temp$parameter,
    p.value = round(result.temp$p.value, digits = (digits + 1))
  )

  class(result) <- c("feR.comp_prop",class(result))
  result
}
feranpre/feR documentation built on Nov. 22, 2022, 2:29 a.m.