通过循环创建数据框每一行的摘要幻灯片

create a summary slide of each row of the dataframe through a loop

我正在尝试创建混合了图和文本的 powerpoint 演示文稿。我有以下示例数据:

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"))

我有以下文本引用了我要绘制的数据框 data

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")

我先定义一个字体样式:

fp_normal <- fp_text(color = "black", font.size = 12, font.family = "calibri")

然后我创建幻灯片并将演示文稿打印为:

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") 

我想为数据框 df 的每一行打印一张新幻灯片,其内容与 text_1

中显示的内容相同

一种方法是包装您的代码以在自定义辅助函数中创建字符串,然后使用 for 循环遍历数据集的行,为每一行添加一张幻灯片,如下所示:

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")