mcj*_*udd 13 r xtable knitr r-markdown
我几乎在编程格式化r输出一个初学者,但我有一个基本的了解knitr,xtable,降价和Pandoc的一个标记格式转换为另一种能力.我想要做的是将R数据帧写入dfHTML表,并将特定颜色应用于满足条件的每一行(例如,df$outcome == 1).但是,我不确定哪个软件包可以通过简单有效的方式完成此任务,但是从浏览一些表格格式线程(xtable线程1,xtable线程2,kable文档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")
Run Code Online (Sandbox Code Playgroud)
与knit2html引用名为"rowcolor_ex.Rmd"的文件,如下图所示:
```{r,echo=FALSE,results='asis',warning=FALSE,message=FALSE}
print(dfxt,
type = "html",
include.rownames = FALSE,)
```
Run Code Online (Sandbox Code Playgroud)
我明白如果我要使用xtable,我会print(dfxt,在Rmd文档中的函数调用部分之后包含一个或多个参数,并且此线程显示add.to.row有意义的参数type = "latex",但不清楚代码将如何更改HTML输出.另外,我不确定引用CSS样式表knit2html是否会覆盖HTML表的格式.
raw*_*awr 16
这是一个使用的解决方案 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)))
Run Code Online (Sandbox Code Playgroud)
编辑
既然htmlTable已经移动到包中htmlTable,并且不再是Gmisc> = 1.0,那么新的方法就是这样做
library('htmlTable')
htmlTable(as.matrix(df), col.rgroup = cols)
Run Code Online (Sandbox Code Playgroud)
这也给出了:

而你的降价代码就是这样
```{r, results='asis'}
htmlTable(as.matrix(df), altcol = cols,
rgroup = '', n.rgroup = rep(1, length(cols)))
```
Run Code Online (Sandbox Code Playgroud)
我的.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)))
```
Run Code Online (Sandbox Code Playgroud)
好吧,不使用颜色(不支持markdown),但是你可以使用粗体或斜体字体高亮显示pandoc.table和一般pander 方法的表格的单元格/行/列:
> library(pander)
> emphasize.rows(which(df$outcome == 2))
> pander(df)
-------------------------
id inputval outcome
---- ---------- ---------
29 0.89 1
*79* *0.69* *2*
*41* *0.64* *2*
*89* *1* *2*
95 0.66 1
5 0.71 1
53 0.54 1
*90* *0.6* *2*
*56* *0.29* *2*
46 0.14 4
96 0.97 1
*46* *0.91* *2*
68 0.69 4
58 0.8 1
11 0.02 3
90 0.48 1
25 0.76 1
5 0.21 4
33 0.32 4
*96* *0.23* *2*
-------------------------
Run Code Online (Sandbox Code Playgroud)