提问人:stephr 提问时间:11/3/2023 最后编辑:stephr 更新时间:11/3/2023 访问量:69
如何让我的 flextable 保留它在 R 中绘制的列表中的元素名称?
How do I get my flextable to retain the names of elements in the list that it draws from in R?
问:
我的 flextable 函数不断将 table_list 的元素名称替换为“var1”、“var2”等。我不想那样。
这是我的数据:
table_list<-list(A03.PREDIABETES = structure(list(Var1 = structure(1:2, levels = c("N",
"Y"), class = "factor"), Freq = c(8L, 3L)), class = "data.frame", row.names = c(NA,
-2L)), A03.GOITER = structure(list(Var1 = structure(1L, levels = "N", class = "factor"),
Freq = 11L), class = "data.frame", row.names = c(NA, -1L)),
A03.GESTATIONAL = structure(list(Var1 = structure(1:2, levels = c("N",
"Y"), class = "factor"), Freq = c(9L, 2L)), class = "data.frame", row.names = c(NA,
-2L)), A03.HASHIMOTO = structure(list(Var1 = structure(1L, levels = "N", class = "factor"),
Freq = 11L), class = "data.frame", row.names = c(NA,
-1L)), A03.THYROID = structure(list(Var1 = structure(1:2, levels = c("N",
"Y"), class = "factor"), Freq = c(10L, 1L)), class = "data.frame", row.names = c(NA,
-2L)), A03.HYPERTHYROID = structure(list(Var1 = structure(1:2, levels = c("N",
"Y"), class = "factor"), Freq = c(10L, 1L)), class = "data.frame", row.names = c(NA,
-2L)), A03.HYPOTHYROID = structure(list(Var1 = structure(1L, levels = "N", class = "factor"),
Freq = 11L), class = "data.frame", row.names = c(NA,
-1L)), A03.OTHER = structure(list(Var1 = structure(1:2, levels = c("N",
"Y"), class = "factor"), Freq = c(10L, 1L)), class = "data.frame", row.names = c(NA,
-2L)), A03.NONE = structure(list(Var1 = structure(1:2, levels = c("N",
"Y"), class = "factor"), Freq = c(7L, 4L)), class = "data.frame", row.names = c(NA,
-2L)))
这是我的代码:
library(data.table)
library(tidyverse)
library(dplyr)
library(ggplot2)
library(writexl)
library(anytime)
library(officer)
library(flextable)
# Create a Word document
doc <- read_docx()
# Add each table to the Word document
for (i in 1:length(table_list)) {
df <- table_list[[i]]
table <- flextable(df)
table <- set_table_properties(table, width = .5)
doc <- doc %>% body_add_flextable(table)
}
# Save the Word document
print(doc, target = "report.docx")
具体来说,标签在这里丢失了: for (i in 1:length(table_list)) { df <- table_list[[i]] 我认为这与通过数字而不是名称访问事物的循环有关。 我尝试过使用元素名称遍历事物。但如果这是解决方案,我还没有弄清楚如何正确地做到这一点。
答:
2赞
nightstand
11/3/2023
#1
您可以为每个表添加标签作为标题。这可以使用 来完成。flextable::set_caption
library(officer)
library(flextable)
doc <- read_docx()
for(i in 1:length(table_list)){
tbl <- table_list[[i]] |>
flextable() |>
set_table_properties(width = 0.5) |>
set_caption(names(table_list)[[i]])
doc <- doc |> body_add_flextable(tbl)
}
print(doc, target = "report.docx")
输出:
评论
baseline
table_list