Search code examples
alignmentknitrkableextra

how to align column title and content in knitr


Just trying to align title of a column to its contents in knitr. what is the function? When I use align = 'c' or position = 'c', it gives me an error:

unused argument (align = "c").

This is my code:

DF_3 <-structure(list(. = structure(c(11L, 6L, 7L, 8L, 13L, 5L, 4L, 2L, 12L, 3L, 1L, 10L, 9L),
                                    .Label = c("B", "D", "E", "F", "G", "H", "H", "H", "I", "J", "M", "N", "V"), class = "f"),
                      HEV.pos = structure(c(3L, 8L, 1L, 6L, 2L, 9L, 8L, 10L, 7L, 3L, 8L, 4L, 5L),
                                          .Label = c("1 (2)", "15", "16", "19", "20", "24", "26", "4 (7)", "6 (11)", "7 (13)"), class = "factor"),
                      HEV.neg = structure(c(9L, 2L, 7L, 1L, 6L, 1L, 7L, 10L, 5L, 4L, 8L, 3L, 5L),
                                          .Label = c("10 (28)", "12 ", "15 ", "17", "18 ", "19 ", "2 ", "4", "7", "9"), class = "factor")),
                 class = "data.frame", row.names = c(NA, -13L)) 


library(knitr)
library(kableExtra)
library(dplyr)

kable(DF_3, format = "html") %>% 
  kable_styling(bootstrap_options = "striped") %>%
  row_spec(1, bold = T) %>% 
  row_spec(6, bold = T) %>%
  column_spec(1, bold = T)

Solution

  • It is not clear to see where you were trying to use the align argument. However, it has to be provided to the kable function. The function documentation stats:

    *Column alignment: a character vector consisting of 'l' (left), 'c' (center) and/or 'r' (right). By default or if align = NULL, numeric columns are right-aligned, and other columns are left-aligned. If length(align) == 1L, the string will be expanded to a vector of individual letters, e.g. 'clc' becomes c('c', 'l', 'c'), unless the output format is LaTeX.

    As some examples:

    knitr::kable(mtcars[1:5, 1:5], caption = "Left Aligned")
    

    enter image description here

    knitr::kable(mtcars[1:5, 1:5], align = "c", caption = "Center Aligned")
    

    enter image description here

    knitr::kable(mtcars[1:5, 1:5], align = c("c", "l", "r", "c", "c"), caption = "Mixed Aligned")
    

    enter image description here