R officer - 将数据框嵌套到分组列表中并将表格导出到带组的 Word Headers

R officer - Nest Dataframe Into Grouped List And Export Tables to Word With Group Headers

我读到一个类似的问题,它帮助我达到了现在的目的,但我正在努力进行下一步。我有一个类似于下面的数据框 -

Product = c("Apple", "Apple", "Banana", "Banana", "Banana", "Carrot", 
            "Carrot") 
Category = c(1, 2, 1, 2, 3, 1, 2) 
Slope = c(2.988, 2.311, 2.181, 6.387, 2.615, 7.936, 3.267) 
df = data.frame(Product, Category, Slope) 

我的 objective 是为每个产品制作一个带有 table 的 Word 报告。 为此,我创建了一个包含数据的列表, flextables,如下-

library(tidyverse)
library(flextable)
library(officer)
test <- df %>%
          group_by(Product) %>%
          nest() %>%
          mutate(data$Product)
          mutate(ftables = map(data, flextable)) %>%
          mutate(ftables = map(ftables, ~ bg(.,
                               bg = '#bfbfbf',
                               part = 'header')))

然后我可以像这样将它传递给 word -

my_doc <- read_docx()
for (i in seq_along(test$ftables)) {
     body_add_flextable(my_doc, test$ftables[[i]]) %>%
     body_add_par(value = "")
}

输出很棒,但不幸的是我失去了识别每个 table 属于哪个产品的任何方法。

我想将产品名称作为标题或在 table 中。哪个都无所谓,但我也不知道该怎么做。

我试图寻找重新引入分组字段 post-nest 的方法,还尝试在 header 的 for 循环中加倍,但最终只是重复了所有 [=每个 header -

下有 34=]s
for (i in seq_along(test$ProductLine)) {
  my_doc <- body_add_par(my_doc, value = test$ProductLine[[i]], style = 
                         'heading 1') %>%
  body_add_par(value = "")
  for (j in seq_along(test$ftables)) {
    my_doc <- body_add_flextable(my_doc, test$ftables[[i]])
  }
}

有没有人知道我可以用什么方法来完成这个?

在第二次尝试循环时,不要添加第一个循环,只需将命令添加到链中...

Product = c("Apple", "Apple", "Banana", "Banana", "Banana", "Carrot", 
            "Carrot") 
Category = c(1, 2, 1, 2, 3, 1, 2) 
Slope = c(2.988, 2.311, 2.181, 6.387, 2.615, 7.936, 3.267) 
df = data.frame(Product, Category, Slope) 

library(tidyverse)
library(flextable)
library(officer)

test <- 
  df %>%
  group_by(Product) %>%
  nest() %>%
  mutate(ftables = map(data, flextable)) %>%
  mutate(ftables = map(ftables, ~ bg(.,
                                     bg = '#bfbfbf',
                                     part = 'header')))

my_doc <- read_docx()

for (i in seq_along(test$Product)) {
  my_doc <- 
    my_doc %>% 
    body_add_par(value = test$Product[[i]], style = 'heading 1') %>% 
    body_add_par(value = "") %>% 
    body_add_flextable(test$ftables[[i]]) %>% 
    body_add_par(value = "")
}

print(my_doc, target = "my_doc.docx")