我正在使用Officer创建一个Word文档,这是一个大表。进入这个表我想插入一些图像。要做到这一点,我使用flextable。以下代码将图像插入到flextable中。
pupil.tbl <- tribble(
~col1, ~col2,
paste("Name:", pupil$name), paste("Class:", pupil.class),
"attendance_graph", "boxall_graph"
)
# add attendance plot
pupil.ft <- flextable(as.data.frame(pupil.tbl))
pupil.ft <- display(
pupil.ft, i=2, col_key = "col1", pattern = "{{att_tbl}}",
formatters = list(
att_tbl ~ as_image(
col1,
src = "attendance.png",
width = 3.3,
height = 1.65)
)
)
)
这很好用,但是我有很多图片要添加,所以我想我会把它抽象成一个函数。但是,当我尝试这样做时,我得到:
data.frame出错(image_src = src,width = width,height = height,stringsAsFactors = FALSE): object&#39; image_file&#39;找不到
这是函数和对函数的调用(目前它使用全局变量来处理除图像路径之外的所有内容)
pupil.ft <- add_img_to_flextable("attendance.png")
add_img_to_flextable <- function(image_file){
return(
display(
pupil.ft, i=2, col_key = "col2", pattern = "{{att_tbl}}",
formatters = list(
att_tbl ~ as_image(
col1,
src = image_file,
width = 3.3,
height = 1.65)
)
)
)
}
答案 0 :(得分:1)
如果在输入data.frame的列中添加src,它应该按预期工作。我无法重现所有内容,因为我没有您的数据和图片。
library(flextable)
library(tibble)
download.file("https://www.r-project.org/logo/Rlogo.png", destfile = "Rlogo.png")
pupil.tbl <- tribble(
~col1, ~col2, ~col3,
"A", "B", "Rlogo.png",
"C", "D", "Rlogo.png"
)
pupil.tbl <- as.data.frame(pupil.tbl)
# display only col1 and col2
pupil.ft <- flextable(pupil.tbl, col_keys = c("col1", "col2") )
add_img_to_flextable <- function(ft, i, j){
display(
ft, i=i, col_key = j, pattern = "{{att_tbl}}",
formatters = list(# use col3 even if not displayed
att_tbl ~ as_image(col3, src = col3, width = 1.29, height = 1)
)
)
}
pupil.ft <- add_img_to_flextable(pupil.ft, i = 2, j = "col2")
pupil.ft
请注意,我对display
函数不满意,我可以看到它的用法太复杂了,我可能会在以后改进这一点。