Generate pptx slides from R
with officer
R
The awesome R package officer has tools to connect R to Office documents. You can use it to generate a PowerPoint document from R.
For example, if you’ve created a bunch of png files from ggplot, you can add them as slides to a PowerPoint document like this:
library(officer)
# Load in a base template ppt
base_ppt <- officer::read_pptx("your_ppt_goes_here.pptx")
# List available slide types
layout_summary(base_ppt)
# Table of images to go on slides and content for the slides
images_to_include <- list.files("figures/png", pattern = "png", full.names = TRUE)
images_to_include <- images_to_include |>
enframe(name = NULL) |>
mutate(title = str_extract(value, "(.*)\\.png", group = 1))
# Loop over all images
for (i in 1:nrow(images_to_include)) {
file_name <- images_to_include$value[i]
slide_title <- images_to_include$title[i]
# Make sure layout and master are from the layout_summary
base_ppt <- add_slide(base_ppt, layout = "Title and Content", master = "Theme")
base_ppt <- ph_with(base_ppt, value = slide_title, location = ph_location_type("title"))
# Image in center of slide
s_s <- slide_size(base_ppt)
s_w <- s_s$width # width of slides
s_h <- s_s$height # width of slides
# Decide image size (numerator is cm, converted to inches)
image_h <- 14.37 / 2.54
image_w <- 19.15 / 2.54
left <- s_w / 2 - image_w / 2
top <- s_h / 2 - image_h / 2
base_ppt <- ph_with(base_ppt,
value = external_img(file_name, height = image_h, width = image_w),
location = ph_location(left = left, top = top), use_loc_size = FALSE)
}
# Save
print(base_ppt, target = "your_output_file.pptx")
# Open
browseURL("your_output_file.pptx")