You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
2.3KB

  1. #' Transform any test function into a valid test function for the table
  2. #'
  3. #' Transform a function into a valid test function for the table
  4. #' Applying the function on a numerical vector should return one value
  5. #' Applying the function on a factor should return nlevels + 1 value, or one value per factor level
  6. #' @param x A vector
  7. #' @param f The function to try to apply, or a formula combining two functions
  8. #' @param group Grouping factor
  9. #' @return The results for the function applied on the vector, compatible with the format of the result table
  10. #' @keywords internal
  11. testify <- function(x, f, group) {
  12. # Extract the name of the function
  13. f %>%
  14. deparse() %>%
  15. Reduce(f = paste0) %>%
  16. substring(2) -> fun
  17. # If eval(f[[2]]) throws an error, then we may be in an rlang-formula
  18. tryCatch(f <- eval(f[[2]]),
  19. error = function(e) {f <<- rlang::as_function(f)})
  20. # Try the function
  21. p <- tryCatch(f(x ~ group)$p.value[1],
  22. error = function(e) {message(e);NaN})
  23. # Return the correct number of rows depending on the variable type
  24. if (is.factor(x)) data.frame(p = c(p, rep(NA, nlevels(x))),
  25. test = c(fun, rep(NA, nlevels(x))),
  26. row.names = NULL, check.names = F, stringsAsFactors = F)
  27. else data.frame(p = p,
  28. test = fun,
  29. row.names = NULL, check.names = F, stringsAsFactors = F)
  30. }
  31. #' Function to choose a statistical test
  32. #'
  33. #' This function takes a variable and a grouping variable as arguments, and returns a statistcal test to use, expressed as a single-term formula.
  34. #'
  35. #' This function uses appropriate non-parametric tests depending on the number of levels (wilcoxon.test for two levels
  36. #' and kruskal.test for more), and fisher.test with fallback on chisq.test on error for factors.
  37. #'
  38. #' @param var The variable to test
  39. #' @param grp The variable for the groups
  40. #' @return A statistical test function
  41. #' @export
  42. tests_auto <- function(var, grp) {
  43. grp <- factor(grp)
  44. if (nlevels(grp) < 2)
  45. ~no.test
  46. else if (is.factor(var)) {
  47. if (tryCatch(is.numeric(fisher.test(var ~ grp)$p.value), error = function(e) F))
  48. ~fisher.test
  49. else
  50. ~chisq.test
  51. } else if (nlevels(grp) == 2)
  52. ~wilcox.test
  53. else
  54. ~kruskal.test
  55. }