tidyHtmlTable
acts as a wrapper function for the htmlTable
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
pivot_longer
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 %>% as_tibble(rownames = "rnames") %>% pivot_longer(names_to = "per_metric", cols = c(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), .groups = 'drop') %>% pivot_longer(names_to = "summary_stat", cols = c(Mean, SD, Min, Max)) %>% ungroup() %>% mutate(gear = paste(gear, "Gears"), cyl = paste(cyl, "Cylinders"))
At this point, we are ready to implement the htmlTable
function.
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
input data.
tidy_summary %>% arrange(per_metric, summary_stat) %>% addHtmlTableStyle(align = "r") %>% tidyHtmlTable(header = gear, cgroup = cyl, rnames = summary_stat, rgroup = per_metric)
tidy_summary %>% arrange(cyl, gear) %>% addHtmlTableStyle(align = "r") %>% tidyHtmlTable(header = summary_stat, cgroup = per_metric, rnames = gear, rgroup = cyl)
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.