使用 kable
创建表时, 有没有办法在 data.frame ' < br >
中的字符串时生成换行符(即 dt'
)有\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()
这与 Automated nicely formated book of lyrics from data.frame using markdown, knitr and glue 有关:
最佳答案
由于文本字符串包含格式为 \n
的换行符,您可以将所有这些替换为等效的 HTML 标记 <br>
.我更喜欢使用 str_replace_all
来自包裹 stringr
但你也可以考虑使用 gsub从基地 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
防止换行符被弄乱。
关于r - 在 HTML kable 表中打印换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51312934/