Adjusting width of tables made with kable() in RMarkdown documents

前端 未结 4 1119
刺人心
刺人心 2020-12-08 14:30

Is it possible to adjust the width of columns when making tables with the kable() function in knitr?

A chunk like this for a table with two columns produces a table

相关标签:
4条回答
  • 2020-12-08 15:06

    My new favorite thing is the flextable package because 1) the tables are beautiful, 2) you can more easily control things like width and font size, and 3) they render well to HTML and Word. Using your data:

    ```{r}
    library(flextable)
    library(magrittr)
    df <- data.frame(x = 1:10, y = 11:20)
    df %>% regulartable() %>% autofit() %>% 
    width(j=~x,width=1) %>% width(j=~y,width=1)
    ```
    

    With both values of width set to 1, the columns are close together:

    If you adjust the last line to width(j=~x,width=2) %>% width(j=~y,width=2) the table looks like this:

    0 讨论(0)
  • 2020-12-08 15:13

    You can try out the kableExtra package.

    kable(x, "html") %>%
      kable_styling(full_width = F)
    
    0 讨论(0)
  • 2020-12-08 15:21

    I know it is a long time since my comment. But as @Tjebo pointed out, my comment is worth an answer, I wanted follow his advise. By defining the table format and adding some CSS styling you can change the size of the like so: knitr::kable(x, format = "html", table.attr = "style='width:30%;'"). This may lead to loosing the table lines. kableExtra offer nice styling tools to add for instance lines.

    library(knitr)
    library(tidyverse)
    library(kableExtra)
    
    df <- data.frame(x = 1:10, y = 11:20)
    
    kable(df, format = "html", table.attr = "style='width:30%;'")
    
    kable(df, format = "html", table.attr = "style='width:30%;'") %>% 
      kableExtra::kable_styling()
    
    0 讨论(0)
  • 2020-12-08 15:23

    I am new to R but possibly my answer will be useful to other newbies here. Experts, please feel free to correct.

    I had a similar issue as the original poster: using kable() my table was off the page and I wanted to rescale. I tried the other answers posted and didn't have success, the reasons may have been that I didn't (at all or properly) install kableExtra or magrittr (the package that allows you to use %>%).

    Ultimately, I ended up using latex_options="scale_down", see below:

    endpoints <- read.delim("D:/RFiles/GenericName/Endpoints.txt",
                header=TRUE, sep="\t", dec=".")
    endpoints_table <- knitr::kable(endpoints,col.names=gsub(" 
                       [.]"," ",names(endpoints)), align="l", 
                       caption = "Endpoints Available")
    kable_styling(endpoints_table,latex_options="scale_down",
                  "striped") %>%
      row_spec(0,bold=TRUE)
    
    0 讨论(0)
提交回复
热议问题