rmarkdown:Word doc中的kable,xtable或tab_df表

时间:2019-07-17 13:26:04

标签: r ms-word r-markdown kable

---
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来生成带有表格的Word文档。当“编织到HTML文档”时,所有表看起来都很好。当“编织到Word”时,xtable不显示表,而tab_dfkable生成的表只有一列:

kable(df) 
cyl
disp
wt
n
4
105.1364
2.285727

1 个答案:

答案 0 :(得分:1)

最近几天我对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()

```  

enter image description here