word文档导出时设置regulartable()的宽度

Set the width of regulartable() when exported in word document

我正在尝试使用 knitrregulartable() 将数据框导出到 word,但我的 table 不适合 word 页面。

---
title: "Correlation table"
author: "mk"
date: "17/01/2022"
output: word_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(scipub)
library(htmlTable)
library(magrittr)
library(mvtnorm)
library(magrittr)
library(flextable)
set.seed(666L)
```


```{r, results='asis',echo=FALSE}
tab<-structure(list(V1 = c("", "", "", "", "", "", "", "", "", ""), 
    V2 = c("-.21**", "", "", "", "", "", "", "", "", ""), V3 = c(".09", 
    "-.03", "", "", "", "", "", "", "", ""), V4 = c("-.23***", 
    ".18**", ".15*", "", "", "", "", "", "", ""), V5 = c(".01", 
    ".07", "-.03", "-.12", "", "", "", "", "", ""), V6 = c(".08", 
    "-.07", ".29***", ".12", "-.22***", "", "", "", "", ""), 
    V7 = c("-.09", ".21**", "-.02", ".13*", ".68***", "-.12", 
    "", "", "", ""), V8 = c(".17*", ".25***", ".05", "-.01", 
    ".32***", ".13*", ".25***", "", "", ""), V9 = c(".16*", "-.20**", 
    ".29***", "-.10", ".08", ".14*", ".01", ".17**", "", ""), 
    V10 = c("-.31***", ".14*", "-.26***", ".05", "-.08", "-.20**", 
    ".02", "-.15*", "-.36***", ""), V11 = c("-.02", "-.13*", 
    "-.29***", "-.06", ".05", "-.05", ".07", "-.08", "-.23***", 
    ".26***"), V12 = c(".03", "-.02", ".29***", ".02", "-.09", 
    ".11", "-.07", ".12", ".20**", "-.32***"), V13 = c("-.10", 
    ".00", ".15*", "-.08", ".00", ".01", ".02", "-.02", ".01", 
    ".10"), V14 = c(".03", "-.17**", "-.15*", "-.09", ".01", 
    ".03", "-.10", "-.26***", "-.04", ".08"), V15 = c(".32***", 
    "-.33***", ".32***", "-.31***", "-.07", ".21**", "-.13", 
    "-.07", ".18**", "-.39***"), V16 = c(".25***", ".00", "-.09", 
    "-.20**", ".01", ".08", ".04", "-.02", "-.21**", "-.15*")), row.names = c("all_fear_fail", 
"all_high_stat_entre", "patience", "risktaking", "posrecip", "negrecip", "altruism", "trust_gps", "lrgdpch2005", "gini_net2000"
), class = "data.frame")


regulartable(tab) %>%
  width(width = 0.5) %>%
  align(align = "center", part = "all")%>%
  theme_zebra() %>% 
  autofit()
```

这有助于:

#convert your dataframe into datatable
library(data.table)

#save your rownames
tab1 <- data.table(tab, keep.rownames = TRUE)

regulartable(tab1) %>%
  align(align = "center", part = "all")%>%
  theme_zebra() %>% 
  fit_to_width(max_width = 7.5)