如何在 RMarkdown 代码块中由 flextable 制成的表格之间添加新行?

问题描述 投票:0回答:1

我正在尝试在代码块中的弹性表之间添加新行。换行符和分页符与第二行的表格标题相互作用,导致其显示。如何在代码块中的表格之间添加换行符而不导致标题出现问题。

我一直在使用的代码如下。带注释的 cat 和knitr 语句是我在表之间添加新行的尝试。这些解决方案来自以下几个问题: https://stackoverflow.com/questions/59824514/new-line-after-table- generated-with-kable https://stackoverflow.com/questions/49561077/creating-a-new-line-within-an-rmarkdown-chunk https://stackoverflow.com/questions/65240436/how-to-add-a-line-break-in-rmarkdown-code

---
title: "Table Loop Example"
output: bookdown::word_document2
---

```{r echo = FALSE, message=FALSE, results='asis'}
library(officer)
library(flextable)
library(tidyverse)

df_1 <- data.frame(replicate(4,sample(0:10,5,rep=TRUE)))
df_2 <- data.frame(replicate(5,sample(5:12,6,rep=TRUE)))

ft <- flextable(df_1) %>% set_caption(caption = "Dataframe 1", autonum = run_autonum(seq_id = "tab", bkm = "tab1")) %>% paginate(init=TRUE, hdr_ftr = TRUE)
flextable_to_rmd(ft)

#cat("  \n")
#cat("\n ")
#cat("<br>")
#cat("<br/>")
#cat("\\")
#cat("\n \\newline \n")
#knitr::asis_output("\n \\newline \n")

ft <- flextable(df_2) %>% set_caption(caption = "Dataframe 2", autonum = run_autonum(seq_id = "tab", bkm = "tab2")) %>% paginate(init=TRUE, hdr_ftr = TRUE)
flextable_to_rmd(ft)
```

猫(“ ") 命令不会对文档产生任何更改。其他命令与第二个表的标题交互。

Table Loop Example
Table 1: Dataframe 1
X1  X2  X3  X4
9   5   7   10
1   3   6   10
9   0   8   2
1   4   5   0
6   7   4   5
 ::: {custom-style=“Table Caption”}
Table 2: Dataframe 2
:::
X1  X2  X3  X4  X5
5   5   11  7   9
12  11  12  9   8
6   6   8   7   7
6   6   7   12  8
12  9   8   9   8
9   7   7   8   6

我希望它看起来像这样:

Table Loop Example
Table 1: Dataframe 1
X1  X2  X3  X4
9   5   7   10
1   3   6   10
9   0   8   2
1   4   5   0
6   7   4   5

Table 2: Dataframe 2
X1  X2  X3  X4  X5
5   5   11  7   9
12  11  12  9   8
6   6   8   7   7
6   6   7   12  8
12  9   8   9   8
9   7   7   8   6
r r-markdown flextable
1个回答
0
投票

这里有一个方法。我不太喜欢它,因为它使用了一些未导出的包函数。但它有效。

```{r echo = FALSE, message=FALSE, results='asis'}
library(officer)
library(flextable)
library(magrittr)

df_1 <- data.frame(replicate(4,sample(0:10,5,rep=TRUE)))
df_2 <- data.frame(replicate(5,sample(5:12,6,rep=TRUE)))

ft1 <- flextable(df_1) %>% 
  set_caption(
    caption = "Dataframe 1", 
    autonum = run_autonum(seq_id = "tab", bkm = "tab1")
  ) %>% paginate(init=TRUE, hdr_ftr = TRUE)
flextable_to_rmd(ft1)

# line break
x <- officer:::to_wml(fpar(run_linebreak()))
cat(flextable:::with_openxml_quotes(x))

ft2 <- flextable(df_2) %>% 
  set_caption(
    caption = "Dataframe 2", 
    autonum = run_autonum(seq_id = "tab", bkm = "tab2")
  ) %>% paginate(init=TRUE, hdr_ftr = TRUE)
flextable_to_rmd(ft2)
```
© www.soinside.com 2019 - 2024. All rights reserved.