I am trying to create a powerpoint presentation with a mix of plots and text. I have the following example data:
data <- structure(list(School_ID = c("J-56124", "T-65451", "D-78544", "TBD",
"B-78664"), Release_Date = structure(c(18659, 19024, 19052, 19052,
19079), class = "Date"), Value = c("11 M", "15 M", "9 M", "3 M", "5 M"),
Type = c("a", "b", "c", "TBD", "TBD")), row.names = c(NA,
-5L), class = c("tbl_df", "tbl", "data.frame"))
I have the following text with references to the data frame data
that I want to plot:
text_1 <- paste0("A: just some text \n",
"some other text \n",
"Type: ", data$Type[1], "\n",
"comments \n",
"Place: LA \n",
"Value: ", paste0('$',formatC(data$Value[1], big.mark=',', format = 'f'))[1], "\n",
"Release Date: ", data$Release_Date[1], "\n",
"School ID: ", data$School_ID[1], "\n",
"more lengthy text to finish the slide")
I first define a font style:
fp_normal <- fp_text(color = "black", font.size = 12, font.family = "calibri")
Then I create the slides and print the presentation as:
my_pres <- read_pptx("my_template4.pptx") %>%
add_slide(., layout = "Title and Content", master = "Office Theme") %>%
ph_with(., value = "my title", location = ph_location_type(type = "title")) %>%
ph_with(., value = "my subtitle", location = ph_location_type(type = "subTitle")) %>%
ph_with(., value = fpar(ftext(text_1, fp_normal)), location = ph_location(left = 0.3, top = 1.2, width = 4, height = 3))
print(my_pres, target = "my_file.pptx")
I want to print a new slide for each row of the dataframe df
with the same content as shown in text_1
CodePudding user response:
One approach would be to wrap your code to create the character string inside a custom helper function then use a for
loop to loop over the rows your dataset to add a slide for each row like so:
library(officer)
library(dplyr)
text_1 <- function(x) {
paste0(
"A: just some text \n",
"some other text \n",
"Type: ", x$Type[1], "\n",
"comments \n",
"Place: LA \n",
"Value: ", paste0("$", formatC(x$Value[1], big.mark = ",", format = "f"))[1], "\n",
"Release Date: ", x$Release_Date[1], "\n",
"School ID: ", x$School_ID[1], "\n",
"more lengthy text to finish the slide"
)
}
my_pres <- read_pptx()
for (i in seq(nrow(data))) {
my_pres <- my_pres %>%
add_slide(., layout = "Title and Content", master = "Office Theme") %>%
ph_with(., value = "my title", location = ph_location_type(type = "title")) %>%
#ph_with(., value = "my subtitle", location = ph_location_type(type = "subTitle")) %>%
ph_with(., value = fpar(ftext(text_1(data[i,]), fp_normal)), location = ph_location(left = 0.3, top = 1.2, width = 4, height = 3))
}
print(my_pres, target = "my_file.pptx")