R - 使用 xtable 或 kable 创建的 HTML 表中的条件行突出显示

标签 r knitr r-markdown xtable

我几乎是编程格式化 R 输出的初学者,但我对 knitr 有基本的了解, xtable 、Markdown 和 Pandoc 将一种标记格式转换为另一种标记格式的能力。我想做的是写一个 R 数据帧 df到 HTML 表格,并将特定颜色应用于满足条件的每一行(例如, df$outcome == 1 )。但是,我不确定哪个包会以简单有效的方式完成此操作,但是通过浏览一些表格格式化线程( xtable thread 1 xtable thread 2 kable documentation 1 ),我收集到了 kablextable可能能够实现我想要的结果。

为了澄清,这是我的可重复示例(使用 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.rowtype = "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)

这也给出了:

enter image description here

你的 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/

相关文章:

r - 设置种子时,示例函数在控制台和针织文档中给出不同的结果

r - 粘贴两个字符列表矩阵

r - 如何根据 R 中的最后一个字符对字符串向量进行排序

滚动最大值(滚动宽度)rollapply 不起作用

r - ggplot2,对 y 轴进行排序

r - 有没有办法在 LaTeX 文档中包含 knitr 文档?

r - 通过 R 中的 knitr 通过 Pandoc 将 Markdown 转换为 HTML5 幻灯片

r - 在 lyx 中使用 tikzDevice 不起作用

r - 打印/保存使用 Rmarkdown 和 Shiny 创建的交互式报告

r - 如何将 Leaflet (for R)-output 包含到 RMarkdown 演示文稿中?