首页 > 解决方案 > R 创建并执行官员字符串

问题描述

我想用我创建的 pdf 创建一个 powerpoint 堆栈。我正试图与官员一起做这件事。它手动工作正常,但我想用代码写出pdf。使用Two Content布局我想将 pdf 的名称写入标题并将 pdf 本身粘贴到正文中。这是我到目前为止开发的代码。

library(officer)
library(magrittr)
pdfList <- c("pdf1.pdf", "pdf2.pdf", "pdf3.pdf")
pdfDir <- "pdfDir"
my_pres<-read_pptx("presentations/blank.pptx") # a blank pptx from powerpoint
pageStart <- "add_slide(layout='Two Content', master='Office Theme') %>% " 
titleListPre <-  "ph_with_text(type = 'title', str = '"
titleListPost <- "') %>% "
imageListPre <- "ph_with_img(src = 'graphics/SSPs/final/"
imageListPost <- "', type = 'body') "

for (i in pdfList) {
  titleString <- paste0(titleListPre, i, titleListPost)
  imageString <- paste0(imageListPre, i, imageListPost)
  finalString <- paste0(pageStart, titleString, imageString)
   my_pres <- my_pres %>%  eval(parse(text = finalString))
}

我遇到的问题是for循环中的最后一行。如果我手动构建该行,如下所示,它可以工作

my_pres <- my_pres %>% add_slide(layout='Two Content', master='Office Theme') %>% ph_with_text(type = 'title', str = 'pdf1.pdf') %>% ph_with_img(src = 'graphics/SSPs/final/pdf1.pdf', type = 'body')

但是 eval/parse 方法不起作用(使用此消息“ invalid 'envir' argument of type 'expression”)并且 as.formula(finalString) 也不起作用

标签: rmagrittrofficer

解决方案


我想出了在哪里进行评估/解析。下面的代码按我的意愿工作。

pageStart <- "add_slide(layout='Two Content', master='Office Theme') %>% " 
titleListPre <-  "ph_with_text(type = 'title', str = '"
titleListPost <- "') %>% "
imageListPre <- "ph_with_img(src = 'graphics/SSPs/final/"
imageListPost <- "', type = 'body') "

for (i in imageList) {
  titleString <- paste0(titleListPre, i, titleListPost)
  imageString <- paste0(imageListPre, i, imageListPost)
  finalString <- paste0("my_pres %>% ",pageStart, titleString, imageString)
  my_pres <- eval(parse(text = finalString))
}

推荐阅读