Skip to content

Instantly share code, notes, and snippets.

@padpadpadpad
Last active February 13, 2020 14:30
Show Gist options
  • Save padpadpadpad/f3b33da8026dfb7d9d2765ee3b238f38 to your computer and use it in GitHub Desktop.
Save padpadpadpad/f3b33da8026dfb7d9d2765ee3b238f38 to your computer and use it in GitHub Desktop.
# load packages
library(flextable)
library(officer)
library(webshot)
library(emmeans)
library(dplyr)
library(tidyr)
# load example data
data(fiber)
?fiber
# run linear model
mod <- lm(strength ~ machine, fiber)
# do pairwise contrasts
emmeans::emmeans(mod, pairwise ~ machine)
# make contrast table
contrasts <- emmeans::emmeans(mod, pairwise ~ machine) %>%
.$contrasts %>%
data.frame() %>%
mutate_if(is.numeric, function(x)round(x, 2)) %>%
mutate_all(as.character)
# super_fp
super_fp <- fp_text(vertical.align = "superscript", font.size = 8, font.family = 'Times')
# italics_fp
italic_fp <- fp_text(italic = TRUE, font.size = 16, font.family = 'Times')
table <- flextable(contrasts) %>%
align(align = 'center', part = 'all') %>%
align(align = 'left', j = 'contrast', part = 'all') %>%
set_header_labels(t.ratio = "t ratio",
p.value = "p value") %>%
add_footer_row(., colwidths = ncol(contrasts), values = '') %>%
compose(., j = "df", part = "header",
value = as_paragraph(as_chunk("d.f.", props = italic_fp))) %>%
compose(., j = "contrast", part = "footer",
value = as_paragraph('P values were adjusted using the Tukey method for comparing a family of 3 estimates')) %>%
font(fontname = 'Times', part = 'all') %>%
fontsize(size = 16, part = 'all') %>%
autofit() %>%
bold(i = ~ p.value < 0.05, j = ~ p.value) %>%
padding(padding.top = 5, part = 'footer')
# save as a png ####
# create an Rmd file
rmd_name <- tempfile(fileext = ".Rmd")
# insert name of table object here
cat("```{r echo=FALSE}\ntable\n```", file = rmd_name)
# render as an html file ----
html_name <- tempfile(fileext = ".html")
render(rmd_name, output_format = "html_document", output_file = html_name )
# get a png from the html file with webshot ----
webshot(html_name, zoom = 2, file = "table_diversity.png",
selector = "body > div.container-fluid.main-container > div.tabwid > table")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment