使用 R 中的“flextable”包,如何将表格插入到 flex 表格的一个单元格中?

Using the "flextable" package in R how do I insert a table into one of the cells of a flex table?

提问人:lavp_theOG 提问时间:11/11/2023 最后编辑:lavp_theOG 更新时间:11/11/2023 访问量:64

问:

我正在尝试使用该包创建 Microsoft Word 文档表。Rflextable

我的尝试:

library(flextable)
library(dplyr)
# create flextables
Outer_table <- data.frame(Number = c(1,2), 
                          table = c(NA,NA)) %>% flextable()
df1 <- data.frame(Species = c("Maple", "Oak", "Hemlock", "Red Pine"),
                  Age = c(40,37,52,64)) %>% flextable()

# combine flextables
Outer_table <- Outer_table %>%
  flextable::compose(j ="Table", i = 1,value = df1)

这会导致错误

x$data[i,j] <值中的错误: 要更换的项目数不是更换长度的倍数。

  1. 有什么方法可以正确地创建 smaler dfs 来创建这样的表?
  2. 此外,我将如何在表格上方添加“按物种划分的平均树龄表”的文本?
R MS-Word Tidyverse Flextable 官员

评论


答:

0赞 Friede 11/11/2023 #1

也许,这让你开始了。我认为提供了帮助:{officer}

library(flextable)
library(officer)

# reformated data 
t1 <- data.frame(Number = c(1, 2), 
                 table = c(NA, NA)) |> 
  flextable() |> theme_box()                  
t2 <- data.frame(Species = c("Maple", "Oak", "Hemlock", "Red Pine"), 
                 Age = c(40, 37, 52, 64)) |> 
  flextable() |> theme_box()

# create docx object 
read_docx() |>
  body_add_par("A table of sth.") |> 
  body_add_flextable(value = t1) |>
  body_add_par("Another table of sth.") |>
  body_add_flextable(value = t2) |>
  print(target = "example.docx")
# you will find example.docx in your current working directory 

我希望可以通过 -functions 实现进一步的样式设置,请参阅此处body_add_*()