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

1

6

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

Marc answered 20/11, 2018 at 13:34 Comment(0)
L
8

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

Lassie answered 20/11, 2018 at 13:47 Comment(2)
Thank you @jsta. Indeed The output is as expected when I perform knit to pdf however, there is no output if I do knit to html (and I want to copy the output to a word document). That might be another question but can you help me with this?Marc
@Marc html answer addedLassie

© 2022 - 2024 — McMap. All rights reserved.