我几乎是编程格式化 R 输出的初学者,但我对 knitr
有基本的了解, xtable
、Markdown 和 Pandoc 将一种标记格式转换为另一种标记格式的能力。我想做的是写一个 R 数据帧 df
到 HTML 表格,并将特定颜色应用于满足条件的每一行(例如, df$outcome == 1
)。但是,我不确定哪个包会以简单有效的方式完成此操作,但是通过浏览一些表格格式化线程( xtable
thread 1 、 xtable
thread 2 、 kable
documentation 1 ),我收集到了 kable
和 xtable
可能能够实现我想要的结果。
为了澄清,这是我的可重复示例(使用 xtable
,但我对使用 kable
或其他包的答案感兴趣):
set.seed(123)
df <- data.frame(id = sample(1:100, 20, replace = TRUE),
inputval = sample(seq(0, 1, by=0.01), 20, replace = TRUE),
outcome = sample(1:4, 20, replace = TRUE))
library(xtable)
dfxt <- xtable(df)
knit2html(input = "~/rowcolor_ex.Rmd",
output = OUTPUTHERE
stylesheet = "STYLESHEET.css")
与
knit2html
引用名为“rowcolor_ex.Rmd”的文件,如下所示:```{r,echo=FALSE,results='asis',warning=FALSE,message=FALSE}
print(dfxt,
type = "html",
include.rownames = FALSE,)
```
我知道如果我要使用
xtable
, 我会在 print(dfxt,
之后包含一个或多个参数Rmd
中函数调用的一部分文档,和 this thread显示 add.to.row
对 type = "latex"
有意义的论点,但不清楚 HTML 输出的代码将如何更改。另外,我不确定是否在 knit2html
中引用 CSS 样式表将覆盖 HTML 表格的格式。
最佳答案
这是使用 Gmisc::htmlTable
的解决方案
set.seed(123)
df <- data.frame(id = sample(1:100, 20, replace = TRUE),
inputval = sample(seq(0, 1, by=0.01), 20, replace = TRUE),
outcome = sample(1:4, 20, replace = TRUE))
cols <- with(df, ifelse(outcome == 1, 'magenta', 'white'))
library(Gmisc)
htmlTable(as.matrix(df), altcol = cols,
rgroup = '', n.rgroup = rep(1, length(cols)))
编辑
自
htmlTable
此后已移至包中,htmlTable
,并且不再在 Gmisc
>= 1.0,新的方法是library('htmlTable')
htmlTable(as.matrix(df), col.rgroup = cols)
这也给出了:
你的 Markdown 代码只是
```{r, results='asis'}
htmlTable(as.matrix(df), altcol = cols,
rgroup = '', n.rgroup = rep(1, length(cols)))
```
我的 .Rmd 看起来像:
---
output:
html_document:
css: ~/knitr.css
---
```{r, results='asis', message=FALSE}
set.seed(123)
df <- data.frame(id = sample(1:100, 20, replace = TRUE),
inputval = sample(seq(0, 1, by=0.01), 20, replace = TRUE),
outcome = sample(1:4, 20, replace = TRUE))
cols <- with(df, ifelse(outcome == 1, 'magenta', 'white'))
library(Gmisc)
htmlTable(as.matrix(df), altcol = cols,
rgroup = '', n.rgroup = rep(1, length(cols)))
```
关于R - 使用 xtable 或 kable 创建的 HTML 表中的条件行突出显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27114926/