在HTML kable表中打印换行符 [英] Printing linebreaks in HTML kable table

查看:113
本文介绍了在HTML kable表中打印换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用kable创建表时,如果data.frame'dt'中的字符串具有\n吗?

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 ?

例如,在这里:

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()

这与使用markdown,knitr和胶水从data.frame自动生成格式良好的歌词书:

推荐答案

由于文本字符串包含格式为\n的换行符,因此您可以用等效的HTML标记<br>替换所有这些换行符.我更喜欢使用软件包stringr中的str_replace_all,但您也可以考虑使用

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

以下是可重现的示例:

---
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)
```

如果不将文件编译为HTML R Markdown输出,也可以使用dt %>% kable(format = "html",escape = FALSE) %>% kable_styling()来显示它.请注意,escape=FALSE可以防止换行符混乱.

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.

这篇关于在HTML kable表中打印换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆