Search code examples
pdfalignmentr-markdownknitrkable

PDF Rmarkdown - Improper Alignment in Multi-line Cells


For some reason, the following code generates a table in which the last column alternates alignment (left, right, center, left, ...). I've tried using \\ as a line breaker instead of \n but that only generated an awkward and large space between each feature. I would prefer if this last column is all centered - anyone have any ideas on why this is happening?

library(knitr)
library(kableExtra)
df <- data.frame(Metric = c("ECG (mV)", "EDA ($\\mu$s)","EMG (mV)", "Temp (C$^\\circ$)","Resp ($\\%$)", 
                            "BVP", "EDA ($\\mu$s)", "Temp (C$^\\circ$)"), 
                 Description = linebreak(c("Electrocardiography", "Electrodermal Activity", "Electromyography", "Body Temperature", "Respiration",
                                           "Blood Volume Pulse", "Electrodermal Activity", "Skin Temperature")), 
                 Features = linebreak(c("Mean \n Std Deviation \n Peaks", "Mean \n Std Deviation", "Mean \n Std Deviation", 
                                        "Mean \n Std Deviation", "Mean \n Std Deviation \n Peaks", 
                                        "Mean \n Std Deviation \n Heart Rate Variability", "Mean \n Std Deviation", 
                                        "Mean \n Std Deviation")))
kable(df, format = "latex", escape = F, align="c") %>%
  group_rows(index = c("RespiBAN Chest Sensor" = 5, "Empatica E4 Wrist Sensor" = 3)) %>%
  kable_styling(bootstrap_options = c("hover"))

table output


Solution

  • Adding align="c" to linebreak should work

    library(knitr)
    library(kableExtra)
    df <- data.frame(Metric = c("ECG (mV)", "EDA ($\\mu$s)","EMG (mV)", "Temp (C$^\\circ$)","Resp ($\\%$)", 
                                "BVP", "EDA ($\\mu$s)", "Temp (C$^\\circ$)"), 
                     Description = linebreak(c("Electrocardiography", "Electrodermal Activity", "Electromyography", "Body Temperature", "Respiration",
                                               "Blood Volume Pulse", "Electrodermal Activity", "Skin Temperature")), 
                     Features = linebreak(c("Mean \n Std Deviation \n Peaks", "Mean \n Std Deviation", "Mean \n Std Deviation", 
                                            "Mean \n Std Deviation", "Mean \n Std Deviation \n Peaks", 
                                            "Mean \n Std Deviation \n Heart Rate Variability", "Mean \n Std Deviation", 
                                            "Mean \n Std Deviation"), align = "c")) #This parameter