Joz*_*zef 6 r knitr r-markdown kable
.Rmd文件的以下内容:
---
title: "Untitled"
output:
html_document: default
---
```{r cars}
mtcars$am <- sprintf("(%s)", as.character(mtcars$am))
knitr::kable(mtcars, format = "html")
```
Run Code Online (Sandbox Code Playgroud)
在渲染到html之后,将显示列<ol><li></li></ol>中的有序列表am,而不是括号中的数字(由生成的数字sprintf).
这是有意的吗?我如何解决这个问题并在括号中显示数字,因为它们在html输出中?
输出knitr::kable似乎很好,显示:
<td style="text-align:left;"> (1) </td>
细节:
format = "html"不能解决问题,因为在现实生活中,我想用css进行高级格式化,例如基于生成的表的类基于Michael Harper接受的答案的快速解决方案可能是这样的方法:
replacechars <- function(x) UseMethod("replacechars")
replacechars.default <- function(x) x
replacechars.character <- function(x) {
x <- gsub("(", "(", x, fixed = TRUE)
x <- gsub(")", ")", x, fixed = TRUE)
x
}
replacechars.factor <- function(x) {
levels(x) <- replacechars(levels(x))
x
}
replacechars.data.frame <- function(x) {
dfnames <- names(x)
x <- data.frame(lapply(x, replacechars), stringsAsFactors = FALSE)
names(x) <- dfnames
x
}
Run Code Online (Sandbox Code Playgroud)
使用示例:
mtcars <- datasets::mtcars
# Create a character with issues
mtcars$am <- sprintf("(%s)", as.character(mtcars$am))
# Create a factor with issues
mtcars$hp <- as.factor(mtcars$hp)
levels(mtcars$hp) <- sprintf("(%s)", levels(mtcars$hp))
replacechars(mtcars)
Run Code Online (Sandbox Code Playgroud)
如果您不想删除format="html"参数,可以尝试使用 HTML 字符实体作为括号 (&lpar和&rpar),然后添加参数escape = FALSE:
```{r cars}
mtcars$am <- sprintf("(%s)", as.character(mtcars$am))
knitr::kable(mtcars, format = "html", escape = FALSE)
```
Run Code Online (Sandbox Code Playgroud)
但仍不完全确定导致错误的原因。看起来括号的特定组合正在被kunit奇怪地处理。