Load R packages

packs <- c("devtools",
           "knitr",
           "MASS",
           "htmlTable")

lapply(packs, function(x) require(x, character.only = T))

install_github("lisaerein/nicetable")
library(nicetable)

help(nicetable)

options(knitr.kable.NA = '.')

Load survey example dataset from the MASS package

head(survey <- survey)

Create a summary table for all results

tab <- nicetable(df = survey,
                  covs = names(survey),
                  type = c(2,1,1,2,2,1,2,2,2,1,2,1))

Choose summary statistics for continuous variables and use 1 decimal place. Use labels instead of variable names.

labs <- c("Gender",
          "Span of writing hand",
          "Span of non-writing hand",
          "Writing hand",
          "Which arm is on top when you fold your arms?",
          "Pulse (bpm)",
          "Which arm is on top when you clap?",
          "Exercise frequency",
          "Smoking frequency",
          "Height (cm)",
          "Which units did students use",
          "Age (years)")

tab <- nicetable(df = survey,
                 covs = names(survey),
                 labels = labs,
                 type = c(2,1,1,2,2,1,2,2,2,1,2,1),
                 stats = c("mean_sd", "median", "iqr", "range"),
                 cont.dec = 1)

Create summary table stratified by gender

tab <- nicetable(df = survey,
                 by = "Sex",
                 covs = names(survey)[-1],
                 type = c(1,1,2,2,1,2,2,2,1,2,1))

Change percentages from row to column percentages and use 2 decimal places. Add a row to the number of non-missing values.

tab <- nicetable(df = survey,
                 by = "Sex",
                 covs = names(survey)[-1],
                 type = c(1,1,2,2,1,2,2,2,1,2,1),
                 percent = 1,
                 perc.dec = 2,
                 dispN = TRUE)

Add p-values for statistical comparisons. Select tests automatically using non-parametric methods.

tab <- nicetable(df = survey,
                 by = "Sex",
                 covs = names(survey)[-1],
                 type = c(1,1,2,2,1,2,2,2,1,2,1),
                 tests = "np")

Remove "All" column. Change striping colors. Add a title. Change to parametric tests.

tab <- nicetable(df = survey,
                 allcol = FALSE,
                 by = "Sex",
                 covs = names(survey)[-1],
                 type = c(1,1,2,2,1,2,2,2,1,2,1),
                 tests = "p",
                 caption = "Table 1: Survey responses by gender",
                 htmltitle = "Survey questions",
                 color = "powderblue")


lisaerein/nicetable documentation built on March 9, 2024, 7:48 a.m.