How can I wrap a cell in a knitr::kable
table cell using \n
?
I want to generate a .rmd file containing some tables where one column needs text wrapping. The places where the wrapping should occur are marked with \n
. I tried (this is a standalone .rmd document):
---
output: pdf_document
---
## A Table with text wrap
```{r cars}
knitr::kable(data.frame(col1 = c("a", "b"), col2 = c("one\ntwo", "three\nfour")))
```
..but this doesn't work. Instead of staying in col2
, the wrapped part lives on the next line of col1
.
Expected output is:
col1 | col2
-------------
a | one
| two
b | three
| four
Solutions using other packages than knitr
are welcome as long as they allow to print (nearly) as nice.
A fire-and-forget solution for flexible dual HTML/PDF of standard tables. It incorporates kableExtra's linebreak function outlined by @snoram.
Assumption: You use <br>
as your line break indicator.
```{r}
knit_table(df1)
```
library(dplyr)
library(knitr)
library(kableExtra)
knit_table <- function(df){
if (is_html_output()) {
df %>%
kable("html", escape = F) %>%
kable_styling()
} else {
df <- data.frame(lapply(df, function(x) {gsub("<br>", "\n", x)}), stringsAsFactors = F)
df %>%
mutate_all(linebreak) %>%
kable("latex", booktabs = T, escape = F)
}
}
df1 <- data.frame(col1 = c("a", "b"),
col2 = c("one<br>two", "three<br>four"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With