kable indent rows with specific hspace for all columns

Viewed 403

The following code add indentations to the 2nd & 4th rows for first column only.

library(kableExtra)
knitr::kable(head(mtcars[ ,1:4]), "latex") %>% 
  add_indent(positions = c(2, 4))

Wondering how to add indentations of specific hspace to the 2nd & 4th rows for all columns. Something like this

library(kableExtra)
knitr::kable(head(mtcars[ ,1:4]), "latex") %>% 
  add_indent(positions = c(2, 4), hspace = "2em", allCols = TRUE)
2 Answers

add_indent is indeed only made for the first column.

A workaround would be to add the indentation manually in your data frame:

head(mtcars) %>%
  mutate_all(., funs(ifelse(row_number() %in% c(2, 4), 
                            paste0("\\hspace{1em}", .), .))) %>%
  kable(format = "latex", booktabs = T, escape = F)

gives:

enter image description here

We can write a version of the add_indent function that adds this option. Doing it this way ensures that kable options such as digits are applied consistently in each row.

add_indent = function(kable_input, positions, allCols = FALSE) {
  out = kableExtra::add_indent(kable_input, positions)
  if (allCols){  
    table_info <- magic_mirror(kable_input)
    for (i in positions + table_info$position_offset) {
      rowtext <- table_info$contents[i]
      table_info$contents[i] <- gsub(' &', paste(' &', kableExtra:::latex_indent_unit('')), rowtext)
      out <- gsub(rowtext, table_info$contents[i], out, fixed = T)
    }
    out <- structure(out, format = "latex", class = "knitr_kable")
    attr(out, "kable_meta") <- table_info
  }  
  return(out)
}


kable(head(mtcars[ ,1:4]), "latex", align = 'l') %>% 
  add_indent(positions = c(2, 4), allCols = T)

enter image description here

Related