tidyHtmlTable acts as a wrapper function for the
function allowing columns to be mapped from the input data to specific htmlTable
parameters in a manner similar to ggplot2.
We'll begin by turning the
mtcars data into a tidy dataset. The
gather function is called to collect 3 performance metrics into a pair
of key and value columns.
library(magrittr) library(tidyr) library(dplyr) library(htmlTable) library(tibble) td <- mtcars %>% rownames_to_column %>% select(rowname, cyl, gear, hp, mpg, qsec) %>% gather(per_metric, value, hp, mpg, qsec)
Now we will compute 4 summary statistics for each of the 3 performance metrics. This will be further grouped by number of cylinders and gears.
tidy_summary <- td %>% group_by(cyl, gear, per_metric) %>% summarise(Mean = round(mean(value), 1), SD = round(sd(value), 1), Min = round(min(value), 1), Max = round(max(value), 1)) %>% gather(summary_stat, value, Mean, SD, Min, Max) %>% ungroup %>% mutate(gear = paste(gear, "Gears"), cyl = paste(cyl, "Cylinders"))
At this point, we are ready to implement the
Essentially, this constructs an html table using arguments similar to the
htmlTable function. However, whereas
htmlTable required the user to manually
arrange the data and specify the column groups, headers, row names, row-groups,
etc., each of these components of the table is mapped to a column within the
Output html table
tidy_summary %>% tidyHtmlTable(header = "gear", cgroup1 = "cyl", cell_value = "value", rnames = "summary_stat", rgroup = "per_metric")
tidy_summary %>% tidyHtmlTable(header = "summary_stat", cgroup1 = "per_metric", cell_value = "value", rnames = "gear", rgroup = "cyl")