I have this code for making a ppt from R:
library(officer)
library(tidyverse)
pres <- read_pptx("E:/Some folder/Document.pptx")
title_slide_2 <- "Trial"
subtitle_slide_2 <- "Some subtitle"
paragraph_slide_2 <- "Something"
#function for making a placeholder
ph <- function(x,ph_value,ph_name){
ph_with(x,value = ph_value, location = ph_location_label(ph_label = ph_name))
}
placeholder <- function(title = NULL,
subtitle = NULL,
table = NULL,
ul = NULL){
if(!is.null(title)){
ph_title <- ph(title, "Title")
}
if(!is.null(subtitle)){
ph_subtitle <- ph(subtitle, "Subtitle")
}
if(!is.null(table)){
ph_table <- ph(table, "Table")
}
if(!is.null(ul)){
ph_ul <- ph(ul, "List")
}
placeholders <- ph_title %>%
ph_subtitle %>%
ph_table %>%
ph_paragraph_1 %>%
ph_paragraph_2 %>%
ph_paragraph_3 %>%
ph_paragraph_4 %>%
ph_paragraph_5 %>%
ph_ul %>%
ph_picture_1 %>%
ph_picture_2 %>%
ph_abbreviations_1 %>%
ph_abbreviations_2 %>%
ph_headline_capture
return(placeholders)
}
my_pres <- pres %>%
remove_slide(index = 1) %>%
add_slide(layout = "Slide 2", master = "Office Theme") %>%
placeholder(title = title_slide_2, subtitle_1 = subtitle_slide_2, paragraph_1 = paragraph_slide_2)
print(my_pres, glue::glue("Doc trial.pptx"))
and it shows me an error stating: Error in x$slide : $ operator is invalid for atomic vectors.
Does anyone have any suggestions on how to change this code? I don't know whether it is ok to make a function for placeholders this way, and whether I made a proper calling of that function, along with passing the arguments
There are several issues with your code. After some refactoring here is a working minimal reproducible example using the default pptx template shipped with officer
:
library(officer)
pres <- read_pptx()
title_slide_2 <- "Trial"
subtitle_slide_2 <- "Some subtitle"
ph <- function(x, ph_value, ph_name) {
ph_with(x, value = ph_value, location = ph_location_label(ph_label = ph_name))
}
placeholder <- function(x,
title = NULL,
subtitle = NULL,
table = NULL,
ul = NULL) {
ph_title <- \(x) if (!is.null(title)) ph(x, title, "Title 1") else x
ph_subtitle <- \(x) if (!is.null(subtitle)) ph(x, subtitle, "Content Placeholder 2") else x
ph_table <- \(x) if (!is.null(table)) ph(x, table, "Content Placeholder 3") else x
x |>
ph_title() |>
ph_subtitle() |>
ph_table()
}
my_pres <- pres |>
#remove_slide(index = 1) %>%
add_slide(layout = "Two Content", master = "Office Theme") |>
placeholder(
title = title_slide_2,
subtitle = subtitle_slide_2
)
print(my_pres, "Doc trial.pptx")