Reputation: 2367
When creating tables using kable
, is there a way to generate a line break (ie < br >
) when string in a data.frame 'dt'
has \n
?
For example, here:
library(data.table);
dt <- fread("https://s3.amazonaws.com/assets.datacamp.com/blog_assets/prince_raw_data.csv")
dt <- dt[301:303,2:6] #take three songs only
library(knitr); library(kableExtra)
kable(dt);
# use this line to view it: dt %>% kable %>% kable_styling()
This relates to Automated nicely formated book of lyrics from data.frame using markdown, knitr and glue:
Upvotes: 2
Views: 3160
Reputation: 15369
As the text strings contain linebreaks in the format \n
, you could replace all of these with the equivalent HTML tag <br>
. I prefer using str_replace_all
from the package stringr
but you could also consider using gsub from base R
Here is a reproducible example:
---
output: html_document
---
```{r}
library(stringr)
dt <- data.frame(text = c("Here is some sample text \nHere is some sample text\n",
"Here is more sample text \nAgain with a linebreak"),
name = c("Name 1", "Name 2"))
dt$text <- stringr::str_replace_all(dt$text, "\\n", "<br>")
knitr::kable(dt)
```
If you aren't compiling the file to an HTML R Markdown output, you can also use dt %>% kable(format = "html",escape = FALSE) %>% kable_styling()
to display it. Note that escape=FALSE
prevents the linebreaks being messed up.
Upvotes: 6