我正在嘗試創建一個混合了圖表和文本的 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
uj5u.com熱心網友回復:
一種方法是包裝您的代碼以在自定義幫助函式中創建字串,然后使用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")

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/456870.html
下一篇:在串列中以五人組申請“for”
