Guest User

Untitled

a guest
Nov 23rd, 2017
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1. quick_summary <- function(df, vars, group = NULL){
  2.  
  3. group_is_null <- is.null(group)
  4.  
  5. coll <- checkmate::makeAssertCollection()
  6.  
  7. checkmate::assert_data_frame(x = df,
  8. add = coll)
  9.  
  10. checkmate::assert_character(x = vars,
  11. add = coll)
  12.  
  13. checkmate::assert_character(x = group,
  14. null.ok = TRUE,
  15. add = coll)
  16.  
  17. checkmate::assert_subset(x = vars,
  18. choices = names(df),
  19. add = coll)
  20.  
  21. if (!group_is_null){
  22. checkmate::assert_subset(x = group,
  23. choices = names(df),
  24. add = coll)
  25. }
  26.  
  27. if (any(vars %in% group)){
  28. in_both <- vars[vars %in% group]
  29. coll$push(paste0("The following variables names are in both 'vars' and 'group': ",
  30. paste0(in_both, collapse = ", ")))
  31. }
  32.  
  33. checkmate::reportAssertions(coll)
  34.  
  35. df <- df[c(vars, group)]
  36.  
  37. checkmate::assert_data_frame(x = df[vars],
  38. types = "numeric",
  39. .var.name = "vars",
  40. add = coll)
  41.  
  42. checkmate::reportAssertions(coll)
  43.  
  44. if (!group_is_null){
  45. group_order <-
  46. lapply(df[group],
  47. function(x) if (is.factor(x)) levels(x) else unique(x))
  48. group_order <- stats::setNames(group_order, group)
  49. }
  50.  
  51. ncount <- function(x, na.rm = TRUE) sum(!is.na(x))
  52.  
  53. df <- tidyr::gather(data = df,
  54. key = !!"variable",
  55. value = !!"value",
  56. dplyr::one_of(vars))
  57.  
  58. df <- dplyr::group_by_at(.tbl = df,
  59. .vars = c("variable", group))
  60.  
  61. df <- dplyr::summarise_at(.tbl = df,
  62. .vars = "value",
  63. .fun = dplyr::funs(
  64. n = ncount,
  65. mean = mean,
  66. sd = sd,
  67. min = min,
  68. median = median,
  69. max = max
  70. ),
  71. na.rm = TRUE)
  72.  
  73. df$variable <- factor(df$variable, levels = vars)
  74.  
  75. if (!group_is_null){
  76. df[group] <- mapply(factor,
  77. x = df[group],
  78. levels = group_order)
  79. }
  80.  
  81. dplyr::arrange_at(.tbl = df, "variable")
  82. }
Add Comment
Please, Sign In to add comment