Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 748
Zhiqiang Wang Avatar asked Nov 27 '25 18:11

Zhiqiang Wang


1 Answers

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

```  

enter image description here

like image 122
JBGruber Avatar answered Nov 29 '25 10:11

JBGruber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!