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.

356 lines
14KB

  1. ---
  2. title: "desctable usage vignette (deprecated)"
  3. output: rmarkdown::html_vignette
  4. vignette: >
  5. %\VignetteIndexEntry{desctable usage vignette (deprecated)}
  6. %\VignetteEngine{knitr::rmarkdown}
  7. %\VignetteEncoding{UTF-8}
  8. ---
  9. ```{r, echo = F, message = F, warning = F}
  10. library(desctable)
  11. options(DT.options = list(#scrollX = T,
  12. info = F,
  13. search = F,
  14. dom = "Brtip",
  15. fixedColumns = T))
  16. knitr::opts_chunk$set(message = F, warning = F, screenshot.force = F)
  17. ```
  18. Desctable is a comprehensive descriptive and comparative tables generator for R.
  19. Every person doing data analysis has to create tables for descriptive summaries of data (a.k.a. Table.1), or comparative tables.
  20. Many packages, such as the aptly named **tableone**, address this issue. However, they often include hard-coded behaviors, have outputs not easily manipulable with standard R tools, or their syntax are out-of-style (e.g. the argument order makes them difficult to use with the pipe (`%>%`)).
  21. Enter **desctable**, a package built with the following objectives in mind:
  22. * generate descriptive and comparative statistics tables with nesting
  23. * keep the syntax as simple as possible
  24. * have good reasonable defaults
  25. * be entirely customizable, using standard R tools and functions
  26. * produce the simplest (as a data structure) output possible
  27. * provide helpers for different outputs
  28. * integrate with "modern" R usage, and the **tidyverse** set of tools
  29. * apply functional paradigms
  30. ----
  31. # Descriptive tables
  32. ## Simple usage
  33. **desctable** uses and exports the pipe (`%>%`) operator (from packages **magrittr** and **dplyr** fame), though it is not mandatory to use it.
  34. The single interface to the package is its eponymous `desctable` function.
  35. When used on a data.frame, it returns a descriptive table:
  36. ```{r}
  37. iris %>%
  38. desctable()
  39. desctable(mtcars)
  40. ```
  41. <br>
  42. As you can see with these two examples, `desctable` describes every variable, with individual levels for factors. It picks statistical functions depending on the type and distribution of the variables in the data, and applies those statistical functions only on the relevant variables.
  43. ## Output
  44. The object produced by `desctable` is in fact a list of data.frames, with a "desctable" class.
  45. Methods for reduction to a simple dataframe (`as.data.frame`, automatically used for printing), conversion to markdown (`pander`), and interactive html output with **DT** (`datatable`) are provided:
  46. ```{r}
  47. iris %>%
  48. desctable() %>%
  49. pander()
  50. mtcars %>%
  51. desctable() %>%
  52. datatable()
  53. ```
  54. <br>
  55. To use `pander` you need to load the package yourself.
  56. Calls to `pander` and `datatable` with "regular" dataframes will not be affected by the defaults used in the package, and you can modify these defaults for **desctable** objects.
  57. The `datatable` wrapper function for desctable objects comes with some default options and formatting such as freezing the row names and table header, export buttons, and rounding of values. Both `pander` and `datatable` wrapper take a *digits* argument to set the number of decimals to show. (`pander` uses the *digits*, *justify* and *missing* arguments of `pandoc.table`, whereas `datatable` calls `prettyNum` with the `digits` parameter, and removes `NA` values. You can set `digits = NULL` if you want the full table and format it yourself)
  58. Subsequent outputs in this vignette will use **DT**.
  59. ## Advanced usage
  60. `desctable` automatically chooses statistical functions if none is provided, using the following algorithm:
  61. * always show N
  62. * if there are factors, show %
  63. * if there are normally distributed variables, show Mean and SD
  64. * if there are non-normally distributed variables, show Median and IQR
  65. For each variable in the table, compute the relevant statistical functions in that list (non-applicable functions will safely return `NA`).
  66. You can specify the statistical functions yourself with the *stats* argument. This argument can either be:
  67. * a function for automatic selection of appropriate statistical functions, depending on the data
  68. * a named list of functions/formulas
  69. The functions/formulas leverage the **tidyverse** way of working with anonymous functions, i.e.:
  70. If a *function*, is is used as is.
  71. If a *formula*, e.g. '~ .x + 1' or `~ . + 1`, it is converted to a function. There are three ways to refer to the arguments:
  72. * For a single argument function, use '.'
  73. * For a two argument function, use '.x' and '.y'
  74. * For more arguments, use '..1', '..2', '..3' etc
  75. This syntax allows you to create very compact anonymous functions, and is the same as in the `map` family of functions from **purrr**.
  76. **Conditional formulas (`condition ~ if_T | if F`) from previous versions are no longer supported!**
  77. ### Automatic function
  78. The default value for the *stats* argument is `stats_auto`, provided in the package.
  79. Several other "automatic statistical functions" are defined in this package: `stats_auto`, `stats_default`, `stats_normal`, `stats_nonnormal`.
  80. You can also provide your own automatic function, which needs to
  81. * accept a dataframe as its argument (whether to use this dataframe or not in the function is your choice), and
  82. * return a named list of statistical functions to use, as defined in the subsequent paragraphs.
  83. ```{r}
  84. # Strictly equivalent to iris %>% desctable() %>% datatable()
  85. iris %>%
  86. desctable(stats = stats_auto) %>%
  87. datatable()
  88. ```
  89. <br>
  90. For reference, here is the body of the `stats_auto` function in the package:
  91. ```{r, echo = F}
  92. print(stats_auto)
  93. ```
  94. <br>
  95. ### Statistical functions
  96. Statistical functions can be **any** function defined in R that you want to use, such as `length` or `mean`.
  97. The only condition is that they return a single numerical value. One exception is when they return a vector of length `1 + nlevels(x)` when applied to factors, as is needed for the `percent` function.
  98. As mentioned above, they need to be used inside a **named list**, such as
  99. ```{r}
  100. mtcars %>%
  101. desctable(stats = list("N" = length, "Mean" = mean, "SD" = sd)) %>%
  102. datatable()
  103. ```
  104. <br>
  105. The names will be used as column headers in the resulting table, and the functions will be applied safely on the variables (errors return `NA`, and for factors the function will be used on individual levels).
  106. Several convenience functions are included in this package.
  107. * `percent`, which prints percentages of levels in a factor
  108. * `IQR`, which re-implements `stats::IQR` but works better with `NA` values
  109. * `is.normal`, which tests for normality using the following method: `length(na.omit(x)) > 30 & shapiro.test(x)$p.value > .1`
  110. Be aware that **all functions will be used on variables stripped of their `NA` values!**
  111. This is necessary for most statistical functions to be useful, and makes **N** (`length`) show only the number of observations in the dataset for each variable.
  112. ### Labels
  113. It is often the case that variable names are not "pretty" enough to be used as-is in a table.
  114. Although you could still edit the variable labels in the table afterwards using sub-setting or string replacement functions, we provide a facility for this using the **labels** argument.
  115. The **labels** argument is a named character vector associating variable names and labels.
  116. You don't need to provide labels for all the variables, and extra labels will be silently discarded. This allows you to define a "global" labels vector and use it for multiple tables even after variable selections.
  117. ```{r}
  118. mtlabels <- c(mpg = "Miles/(US) gallon",
  119. cyl = "Number of cylinders",
  120. disp = "Displacement (cu.in.)",
  121. hp = "Gross horsepower",
  122. drat = "Rear axle ratio",
  123. wt = "Weight (1000 lbs)",
  124. qsec = "¼ mile time",
  125. vs = "V/S",
  126. am = "Transmission",
  127. gear = "Number of forward gears",
  128. carb = "Number of carburetors")
  129. mtcars %>%
  130. dplyr::mutate(am = factor(am, labels = c("Automatic", "Manual"))) %>%
  131. desctable(labels = mtlabels) %>%
  132. datatable()
  133. ```
  134. <br>
  135. ----
  136. # Comparative tables
  137. ## Simple usage
  138. Creating a comparative table (between groups defined by a factor) using `desctable` is as easy as creating a descriptive table.
  139. It leverages the `group_by` function from **dplyr**:
  140. ```{r}
  141. iris %>%
  142. group_by(Species) %>%
  143. desctable() -> iris_by_Species
  144. iris_by_Species
  145. ```
  146. <br>
  147. The result is a table containing a descriptive sub-table for each level of the grouping factor (the statistical functions rules are applied to each sub-table independently), with the statistical tests performed, and their p values.
  148. When displayed as a flat dataframe, the grouping header appears in each variable name.
  149. You can also see the grouping headers by inspecting the resulting object, which is a nested list of dataframes, each dataframe being named after the grouping factor and its levels (with sample size for each).
  150. ```{r}
  151. str(iris_by_Species)
  152. ```
  153. <br>
  154. You can specify groups based on any variable, not only factors:
  155. ```{r}
  156. # With pander output
  157. mtcars %>%
  158. group_by(cyl) %>%
  159. desctable() %>%
  160. pander()
  161. ```
  162. <br>
  163. You can also specify groups based on an expression
  164. ```{r}
  165. # With datatable output
  166. iris %>%
  167. group_by(Petal.Length > 5) %>%
  168. desctable() %>%
  169. datatable()
  170. ```
  171. <br>
  172. Multiple nested groups are also possible:
  173. ```{r, message = F, warning = F}
  174. mtcars %>%
  175. dplyr::mutate(am = factor(am, labels = c("Automatic", "Manual"))) %>%
  176. group_by(vs, am, cyl) %>%
  177. desctable() %>%
  178. datatable()
  179. ```
  180. <br>
  181. In the case of nested groups (a.k.a. sub-group analysis), statistical tests are performed only between the groups of the deepest grouping level.
  182. Statistical tests are automatically selected depending on the data and the grouping factor.
  183. ## Advanced usage
  184. `desctable` automatically chooses statistical functions if none is provided, using the following algorithm:
  185. * if the variable is a factor, use `fisher.test`
  186. * if the grouping factor has only one level, use the provided `no.test` (which does nothing)
  187. * if the grouping factor has two levels
  188. * and the variable presents homoskedasticity (p value for `var.test` > .1) and normality of distribution in both groups, use `t.test(var.equal = T)`
  189. * and the variable does not present homoskedasticity (p value for `var.test` < .1) but normality of distribution in both groups, use `t.test(var.equal = F)`
  190. * else use `wilcox.test`
  191. * if the grouping factor has more than two levels
  192. * and the variable presents homoskedasticity (p value for `bartlett.test` > .1) and normality of distribution in all groups, use `oneway.test(var.equal = T)`
  193. * and the variable does not present homoskedasticity (p value for `bartlett.test` < .1) but normality of distribution in all groups, use `oneway.test(var.equal = F)`
  194. * else use `kruskal.test`
  195. You can specify the statistical test functions yourself with the *tests* argument. This argument can either be:
  196. * a function for automatic selection of appropriate statistical test functions, depending on the data
  197. * a named list of statistical test functions
  198. Please note that the statistical test functions **must** be given as *formulas* so as to capture the name of the test to display in the table.
  199. **purrr** style formulas are also actepted, as with the statistical functions.
  200. This also allows to specify optional arguments of such functions, and go around non-standard test functions (see **Statistical test functions**).
  201. ### Automatic function
  202. The default value for the *tests* argument is `tests_auto`, provided in the package.
  203. You can also provide your own automatic function, which needs to
  204. * accept a variable and a grouping factor as its arguments, and
  205. * return a single-term formula containing a statistical test function.
  206. This function will be used on every variable and every grouping factor to determine the appropriate test.
  207. ```{r}
  208. # Strictly equivalent to iris %>% group_by(Species) %>% desctable() %>% datatable()
  209. iris %>%
  210. group_by(Species) %>%
  211. desctable(tests = tests_auto) %>%
  212. datatable()
  213. ```
  214. <br>
  215. For reference, here is the body of the `tests_auto` function in the package:
  216. ```{r, echo = F}
  217. print(tests_auto)
  218. ```
  219. <br>
  220. ### Statistical test functions
  221. You can provide a named list of statistical functions, but here the mechanism is a bit different from the *stats* argument.
  222. The list must contain either `.auto` or `.default`.
  223. * `.auto` needs to be an automatic function, such as `tests_auto`. It will be used by default on all variables to select a test
  224. * `.default` needs to be a single-term formula containing a statistical test function that will be used on all variables
  225. You can also provide overrides to use specific tests for specific variables.
  226. This is done using list items named as the variable and containing a single-term formula function.
  227. ```{r}
  228. iris %>%
  229. group_by(Petal.Length > 5) %>%
  230. desctable(tests = list(.auto = tests_auto,
  231. Species = ~chisq.test)) %>%
  232. datatable()
  233. ```
  234. <br>
  235. ```{r}
  236. mtcars %>%
  237. dplyr::mutate(am = factor(am, labels = c("Automatic", "Manual"))) %>%
  238. group_by(am) %>%
  239. desctable(tests = list(.default = ~wilcox.test,
  240. mpg = ~t.test)) %>%
  241. datatable()
  242. ```
  243. Here's an example of **purrr** style function:
  244. ```{r}
  245. iris %>%
  246. group_by(Petal.Length > 5) %>%
  247. desctable(tests = list(.auto = tests_auto,
  248. Petal.Width = ~oneway.test(., var.equal = T)))
  249. ```
  250. <br>
  251. As with statistical functions, **any** statistical test function defined in R can be used.
  252. The conditions are that the function
  253. * accepts a formula (`variable ~ grouping_variable`) as a first positional argument (as is the case with most tests, like `t.test`), and
  254. * returns an object with a `p.value` element.
  255. Several convenience function are provided: formula versions for `chisq.test` and `fisher.test` using generic S3 methods (thus the behavior of standard calls to `chisq.test` and `fisher.test` are not modified), and `ANOVA`, a partial application of `oneway.test` with parameter *var.equal* = T.