R ReporteRs:将正则表对象添加到pptx演示文稿中

时间:2018-06-20 17:21:10

标签: r flextable reporters officer

由于要显示的列名称在语法上无效,因此我无法使用ReporteRs包将flextable添加到PowerPoint演示文稿中。

因此,显然flextable仅接受具有语法有效列名的数据帧,这尤​​其意味着名称不能为空字符串,也不能包含空格。 我的第一个解决方案是仅使用regulartable函数,该函数效果很好。但是当我随后想要将我的常规表对象添加到PowerPoint演示文稿中时,它告诉我只能添加柔性表对象(...并且圆度开始...)。

最小示例:

x <- c('a', 'b')
y <- c(1, 2)
d <- data.frame(x, y)
names(d) <- c(" ", "this column") #not syntactically valid column names!

#trying to call flextable(d) leads to an error
#so, try to use regulartable:
table <- regulartable(x)

#now try to create a pptx with this:
mySlides <- pptx()
mySlides <- addSlide(mySlides, 'Blank')
mySlides <- addFlexTable(mySlides, flextable = test) #Error: argument flextable must be a FlexTable object.

有人知道如何解决此问题吗?

如果我知道如何在幻灯片中添加可恢复规则,或者如何使flextable接受空的或包含空格的列名,我会很高兴。

在此先感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

flextable设计用于officer,而不是ReporteRs。请注意,由于与Java> = 9不兼容,软件包ReporteRs将在2018年7月16日从CRAN中删除,软件包officer将替换ReporteRs

您的代码应类似于:

library(flextable)
library(officer)

x <- c('a', 'b')
y <- c(1, 2)
d <- data.frame(x, y)
names(d) <- c(" ", "this column") #not syntactically valid column names!
table <- regulartable(d)

ppt <- read_pptx()
ppt <- add_slide(ppt, layout = "Title and Content", master = "Office Theme")
ppt <- ph_with_flextable(ppt, value = table, type = "body") 

print(ppt, target = "example.pptx")

关于列名。您不必仅显示data.frame即可更改它们的名称。您可以使用不同的功能来做到这一点:

library(flextable)
library(officer)

x <- c('a', 'b')
y <- c(1, 2)
d <- data.frame(x, y)

meta <- data.frame(
  col_keys = c("x", "y"), 
  upper_labels = c("hi", "world"), 
  labels = c(" ", "this column"), 
  stringsAsFactors = FALSE)

table <- regulartable(d)
table <- set_header_df( table, mapping = meta )

d <- data.frame(a = x, b = y)# must not contain x as set_header_labels first arg is also x...
ft <- regulartable(d)
ft <- set_header_labels( ft, a = "", b = "this column" )

ppt <- read_pptx()
ppt <- add_slide(ppt, layout = "Two Content", master = "Office Theme")
ppt <- ph_with_flextable(ppt, value = table, type = "body", index = 1) 
ppt <- ph_with_flextable(ppt, value = ft, type = "body", index = 2) 

print(ppt, target = "example.pptx")