gpt4 book ai didi

r - 在 HTML kable 表中打印换行符

转载 作者:行者123 更新时间:2023-12-02 00:32:33 27 4
gpt4 key购买 nike

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

enter image description here

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

enter image description here

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

关于r - 在 HTML kable 表中打印换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51312934/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com