5

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

ecjb
  • 5,169
  • 12
  • 43
  • 79

1 Answers1

7

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

jsta
  • 3,216
  • 25
  • 35
  • 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? – ecjb Nov 20 '18 at 13:56
  • @ecjb html answer added – jsta Nov 20 '18 at 14:04