Aligning Columns with knitr kable function

前端 未结 3 1416
青春惊慌失措
青春惊慌失措 2021-01-07 17:54

I am performing a simple task: creating a table and outputting it using R Markdown to pdf as follows:

library(knitr)
kable(datatabl         


        
相关标签:
3条回答
  • 2021-01-07 18:24

    You want to feed kable a vector of alignment strings equal to the number of columns. As mentioned in the help file,

    the alignment of columns: a character vector consisting of 'l' (left), 'c' (center) and/or 'r' (right); by default, numeric columns are right-aligned, and other columns are left-aligned; if align = NULL, the default alignment is used.

    Here is a reproducible example.

    Without any alignment values, character columns are left-aligned and numeric columns are right-aligned as you can see below.

    library(knitr)
    
    kable(head(mtcars[1:5]))
    

    which returns

    |                  |  mpg| cyl| disp|  hp| drat|
    |:-----------------|----:|---:|----:|---:|----:|
    |Mazda RX4         | 21.0|   6|  160| 110| 3.90|
    |Mazda RX4 Wag     | 21.0|   6|  160| 110| 3.90|
    |Datsun 710        | 22.8|   4|  108|  93| 3.85|
    |Hornet 4 Drive    | 21.4|   6|  258| 110| 3.08|
    |Hornet Sportabout | 18.7|   8|  360| 175| 3.15|
    |Valiant           | 18.1|   6|  225| 105| 2.76|
    

    To get the numeric columns center-aligned, while keeping the character column right aligned, I used the following.

    kable(head(mtcars[1:5]), align=rep('c', 5))
    
    
    |                  | mpg  | cyl | disp | hp  | drat |
    |:-----------------|:----:|:---:|:----:|:---:|:----:|
    |Mazda RX4         | 21.0 |  6  | 160  | 110 | 3.90 |
    |Mazda RX4 Wag     | 21.0 |  6  | 160  | 110 | 3.90 |
    |Datsun 710        | 22.8 |  4  | 108  | 93  | 3.85 |
    |Hornet 4 Drive    | 21.4 |  6  | 258  | 110 | 3.08 |
    |Hornet Sportabout | 18.7 |  8  | 360  | 175 | 3.15 |
    |Valiant           | 18.1 |  6  | 225  | 105 | 2.76 |
    

    The following text, if copied into an .Rmd file, will return the table, formatted as desired as a pdf file.

    ---
    title: "Untitled"
    output: pdf_document
    ---
    
    this thing
    
    ```{r table1, as.is=TRUE}
    library(knitr)
    
    kable(head(mtcars[1:5]))
    
    ```
    
    
    is not a centered table, while this thing
    
    ```{r table2, as.is=TRUE}
    
    kable(head(mtcars[1:5]), align=rep('c', 5))
    
    ```
    
    is a centered table.
    
    0 讨论(0)
  • 2021-01-07 18:26

    Even easier: kable(mtcars, align = "l") works just fine!

    0 讨论(0)
  • 2021-01-07 18:35

    You can also use the length function to create a vector for all rows in a vector/dataframe without having to hard code a length. The example below left-aligns all the columns in the mtcars data frame no matter the length.

     kable(mtcars, align=rep('l', length(mtcars[,1])))
    
    0 讨论(0)
提交回复
热议问题