You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R中officer包遇try/is.error失效时如何跳过错误留空白

原有方案失效原因
  • try()直接包裹管道后的ph_with():%>%管道会将前一步生成的PPT对象作为第一个参数传入紧跟在管道后的函数。你写%>% try(ph_with(...))时,PPT对象被传给了try()而非ph_with(),ph_with()拿不到PPT操作对象,自然无论绘图是否正常都无法完成插入。
  • BBmisc::is.error()判断失效:你调用时传入的是字符串"good_plot"/"error_plot",而非绘图变量本身,字符串不属于错误类,因此永远返回FALSE。同时if_else直接接在管道后也存在上述参数传递错误,且分支逻辑里的绘图对象、插入位置也存在混淆。
可行实现方案

写一个适配管道操作的安全插入辅助函数,提前判断绘图有效性:有效则正常插入,无效则插入空白内容占位,全程不会中断运行,无需依赖额外第三方包做错误判断。

# 定义安全插入函数:第一个参数为管道传入的PPT对象,第二个传绘图对象/绘图表达式,第三个传插入位置
safe_insert_plot <- function(ppt, plot_input, loc) {
  # 对传入的绘图逻辑做错误捕获
  plot_res <- try(plot_input, silent = TRUE)
  if (inherits(plot_res, "try-error")) {
    # 捕获到错误则插入空白占位
    ppt <- ph_with(ppt, value = empty_content(), location = loc)
  } else {
    # 无错误则正常插入绘图
    ppt <- ph_with(ppt, value = plot_res, location = loc)
  }
  return(ppt)
}

使用时直接把原有的ph_with替换为该函数即可,不需要提前用try()包裹绘图生成逻辑,示例代码如下:

sample <- blank_deck %>%
  add_slide(layout = "Title Slide", master = "Office Theme") %>%
  ph_with(value = "My Title", ph_location_label(ph_label = "Title 1")) %>%
  add_slide(layout = "Blank", master = "Office Theme") %>%
  # 插入正常绘图
  safe_insert_plot(
    plot_input = ggplot(data = iris, aes(x = Species, y = Sepal.Length)) + geom_col(),
    loc = my_location_1
  ) %>%
  # 插入存在错误的绘图,自动保留空白
  safe_insert_plot(
    plot_input = ggplot(data = iris, aes(x = Species, y = Sepal.Length)) + geom_col() + facet_wrap(~Species2),
    loc = my_location_2
  ) %>%
  add_slide(layout = "Title Slide", master = "Office Theme") %>%
  ph_with(value = "End", ph_location_label(ph_label = "Title 1")) %>%
  print(target = '/home/define/your/pathway/mydeck.pptx')

补充:如果需要在出错位置显示错误提示文本,只需要把empty_content()替换为你需要展示的文本、占位符即可,逻辑不需要调整。

内容的提问来源于stack exchange,提问作者J.Sabree

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 12:39:15