Search code examples
rline-breakskableextra

R - kableExtra - Trouble inserting linebreak in html format in a cell containing string


I want to insert a linebreak into a cell of text but can't. In the example below, I want to insert a linebreak between the string group 1.1 and group1.2

I tried to read the documentation ("Best Practice for newline in LaTeX table") but couldn't solve the problem

Here is the code:

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

mydf <- data.frame(
  # group = rep(letters[1:4], each = 2),
  row = c(1:8),
  group = c("group 1.1 \n group1.2", "group 2", "group 3", "group 4", "group 5", "group 6", "group 7", "group 8")
)

mydf %>%
# mutate_all(linebreak) %>%
kable() %>%
   kable_styling()

If I insert mutate_all(linebreak) %>% it doesn't solve the problem neither


Solution

  • pdf

    I was able to get it to work for pdf by setting kable(escape = FALSE):

    library(dplyr)
    library(knitr)
    library(kableExtra)
    
    mydf <- data.frame(
      # group = rep(letters[1:4], each = 2),
      row = c(1:8),
      group = c("group 1.1\ngroup1.2", "group 2", "group 3", "group 4", "group 5", "group 6", "group 7", "group 8")
    )
    
    mydf %>%
      mutate_all(linebreak) %>%
      kable("latex", escape = FALSE) %>%
      kable_styling()
    

    html

    mydf <- data.frame(
      # group = rep(letters[1:4], each = 2),
      row = c(1:8),
      group = c("group 1.1<br>group1.2", "group 2", "group 3", "group 4", "group 5", "group 6", "group 7", "group 8")
    )
    
    mydf %>%
      kable("html", escape = FALSE) %>%
      kable_styling()
    

    See: Printing linebreaks in HTML kable table