【发布时间】:2022-01-05 03:30:03
【问题描述】:
如何在数据框中插入转义字符?
这对于将文本数据格式化成表格包很有用。
我们可以为每个表包使用一个通用解决方案(我希望)。
但是现在我们应该针对每种情况采用很多方法(取决于库和输出格式:pdf、html)。
真的很不舒服!
例如,我们有下一个数据
df <- data.frame("names" = c("a long long long long long ... pretty long name of the our story","Here is also long, but a little shorter"))
我们看到正常输出
names
1 a long long long long long ... pretty long name of the our story
2 Here is also long, but a little shorter
但是我们如何才能实现这个输出(“\n”)?
names
1 a long long long long long
... pretty long name of the our story
2 Here is also long, but a little shorter
我答应添加一个简单的例子:
编织成 HTML,在 PDF 中不起作用
```{r warning = FALSE, echo = FALSE, message=FALSE, include=FALSE,}
library(flextable)
library(gt)
#data
df <- data.frame("names" = c("a long long long \n long long ... <br> pretty long name of the our story","Here is also long, but a little shorter"))
#table one
table3 <- flextable(df)
table3 <- set_table_properties(table3, layout = "autofit", width = .5)
table3
#table two
table4 <- gt(df) %>% fmt_markdown(columns = everything())
table4
```
<center>
<caption>Table in flextable </caption>
</center>
`r table3`
<center>
<caption>Table in gt </caption>
</center>
`r table4`
在第一种情况下 - 工作\n,在第二种情况下 - /br/ 只有两个包!
【问题讨论】:
-
听起来你想要
stringr::str_wrap()这样的东西。 -
@RitchieSacramento 很有趣。我现在尝试用
str_wrap来完成我的任务。之后返回。但问题仍然存在。在没有任何花里胡哨的情况下嵌入转义会很酷。 -
@RitchieSacramento 不,不能做出想要的输出(
-
您可以在单元格值的所需位置将换行符包含为“\n”,然后使用huxtable 包打印它:huxtable::as_huxtable(df) 这样打印out 将是一个表格,其中“\n”被转换为实际的换行符......不确定这是否是你要找的
-
@manro 你到底想达到什么目的......可能你正在寻找在降价中打印一个表格,其中换行符是这样显示的?如果是这样, kableExtra 可能是一个选项,如 here 所解释的
标签: r dataframe r-markdown escaping