rmarkdown:Word 文档中的 kable、xtable 或 tab_df 表

rmarkdown: kable, xtable or tab_df tables in Word doc

---
output:
  word_document: default
---

```{r setup, include=FALSE}
data("mtcars")
library(tidyverse)
library(xtable)
library(sjPlot)
library(kableExtra)
```

```{r, results='asis'}
df <- mtcars %>% 
group_by(cyl) %>% 
summarise(disp = mean(disp), 
        wt = mean(wt), 
        n = n()
)
kable(df)

# tab_df(df)
# xtable(df) 
```    

我已经尝试 xtabletab_dfkable 生成带有 table 的 word 文档。当 "knit to HTML document" 时,所有 table 看起来都很好。当 "knit to Word"、xtable 不显示 table 而 tab_dfkable 产生只有一列的 table:

kable(df) 
cyl
disp
wt
n
4
105.1364
2.285727

最近几天我对 flextable 进行了相当多的试验,当您必须使用 Word 时,它可能是最佳选择:

---
output:
  word_document: default
---

```{r setup, include=FALSE}
data("mtcars")
library(tidyverse)
library(flextable)
```

```{r, results='asis'}
mtcars %>% 
group_by(cyl) %>% 
summarise(disp = mean(disp), 
        wt = mean(wt), 
        n = n()
) %>% 
  flextable() %>% 
  align(part = "all") %>% # left align
  set_caption(caption = "Table 1: Example") %>% 
  font(fontname = "Calibri (Body)", part = "all") %>% 
  fontsize(size = 10, part = "body") %>% 
  # add footer if you want
  # add_footer_row(values = "* p < 0.05. ** p < 0.01. *** p < 0.001.", 
  #                colwidths = 4) %>% 
  theme_booktabs() %>% # default theme
  autofit()

```