rmarkdown: kable, xtable or tab_df tables in Word doc

旧街凉风 提交于 2020-02-05 04:22:28

问题


---
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) 
```    

I have tried xtable, tab_df, and kable to generate a word document with a table. When "knit to HTML document", all tables looked fine. When "knit to Word", xtable didn't show the table while tab_df and kable produced a table with only one column:

kable(df) 
cyl
disp
wt
n
4
105.1364
2.285727

回答1:


I experimented with flextable quite a bit the last few days and it might be the best option when you have to work with 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()

```  



来源:https://stackoverflow.com/questions/57076993/rmarkdown-kable-xtable-or-tab-df-tables-in-word-doc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!