Home > OS >  Aligning text in kableExtra table
Aligning text in kableExtra table

Time:07-24

I am making a Latex pdf in R markdown but am having problems making tables that contain text with the kableExtra package.

When I use the 'align =' argument in Kable() it aligns only the headings and not the full text. The table returned looks like what is below, with the first row of main body aligned left, the next row centre aligned, and the last row right aligned!!

Please help me get it all centre aligned!

Table that gets produced

Code:

library(knitr)
library(kableExtra)

df <- data.frame(c("Title","Title", "Title"), 
                linebreak(c("The Main Text\n Main Text\n Text", "The Main Text\n Main Text\n Text", "The Main Text\n Main Text\n Text")),
                linebreak(c("The Main Text\n Main Text\n Text", "The Main Text\n Main Text\n Text", "The Main Text\n Main Text\n Text")),
                linebreak(c("The Main Text\n Main Text\n Text", "The Main Text\n Main Text\n Text", "The Main Text\n Main Text\n Text")))

kable(df, align="c", col.names = c("","Title","Title", "Title"), escape = FALSE) %>%
  kable_styling(latex_options="HOLD_position")

EDIT:

Here is the reproduced code with yaml,

---
title: 
author: 
date:
abstract:
output:
  pdf_document:
    toc: yes
    toc_depth: 2
  editor_options: 
  markdown: 
    wrap: 72
---
knitr::opts_chunk$set(echo = TRUE)
library(knitr)
library(kableExtra)

df <- data.frame(c("Title","Title", "Title"), 
                linebreak(c("The Main Text\n Main Text\n Text", "The Main Text\n Main Text\n Text", "The Main Text\n Main Text\n Text")),
                linebreak(c("The Main Text\n Main Text\n Text", "The Main Text\n Main Text\n Text", "The Main Text\n Main Text\n Text")),
                linebreak(c("The Main Text\n Main Text\n Text", "The Main Text\n Main Text\n Text", "The Main Text\n Main Text\n Text")))

kable(df, align="c", col.names = c("","Title","Title", "Title"), escape = FALSE) %>%
  kable_styling(latex_options="HOLD_position")

CodePudding user response:

I think the problem is with the specification of your df. Function linebreak has an align argument that is being set when you are creating df. You need to specify the alignment when creating df

df <- data.frame(c("Title","Title", "Title"), 
                linebreak(c("The Main Text\n Main Text\n Text", "The Main Text\n Main Text\n Text", "The Main Text\n Main Text\n Text"), align = 'c'),
                linebreak(c("The Main Text\n Main Text\n Text", "The Main Text\n Main Text\n Text", "The Main Text\n Main Text\n Text"), align = 'c'),
                linebreak(c("The Main Text\n Main Text\n Text", "The Main Text\n Main Text\n Text", "The Main Text\n Main Text\n Text"), align = 'c'))

Also, following documentation from kableExtra it is recommended to add booktabs = T and escape = F when working with LaTex tables. E.g.:

df %>% kbl(booktabs = T, escape = F,
  col.names = c("","Title","Title", "Title"), align = 'c')
  • Related