我下面的答案真的很愚蠢..这是正确的方法:
此功能通过css.cell 参数内置于htmlTable:
css.cell 元素允许您向表格单元格添加任何可能的 CSS 样式。如果您提供向量,则假定样式应在整个列中重复。如果您提供与 x 参数大小相同的矩阵。如果有ncol(x) + 1,第一行将对应rowname 样式。相应地,如果大小为nrow(x) + 1,则假定第一行为标题行。
所以基本上你只需要为每个单元格定义一个样式矩阵:
x <- head(cars)
## indices defining where the styles go
where <- rbind(c(2,2), c(2,1), c(5,2))
style <- c('background-color: red; color: white;',
'border: solid 1px;',
'font-weight: 900; color: blue;')
css.cell <- matrix('', nrow(x), ncol(x))
css.cell[where] <- style
# [,1] [,2]
# [1,] "" ""
# [2,] "border: solid 1px;" "background-color: red; color: white;"
# [3,] "" ""
# [4,] "" ""
# [5,] "" "font-weight: 900; color: blue;"
# [6,] "" ""
htmlTable(head(cars), css.cell = css.cell)
除非您来回交换,否则很难分辨,但此表中的间距与下面的类似表中的间距略有不同。 inject_div 示例看起来更加居中。
有点晚了,但@CyrusMohammadian 对我的其他答案发表了评论,并且由于评论/问题与此相同,我将在此处添加答案,而不是编辑我的答案(略)不同的问题。
表格可能会变得复杂,每个人都有他们想要的不同功能。我认为Max 不可能为它们都内置解决方案。
因此,我认为最简单的方法是(hackily)将一些 html/css 注入到您的表中(您也可以在运行 htmlTable 之后执行此操作,即直接在 html 代码中,但我认为这更容易):
#' Inject div
#'
#' Inject an html division tag with style attribute.
#'
#' @param x a matrix or data frame
#' @param where an \code{nx2} matrix of row and column indices or vector (of
#' the form c(row, col, row, col, ...)) specifying which cells to select
#' @param style vector of character string(s) applied to each cell, recycled
#' if necessary
inject_div <- function(x, where, style = 'background-color: lightgrey; border: solid 1px') {
if (!all(sapply(style, nzchar)))
return(x)
where <- matrix(where, ncol = 2L, byrow = !is.matrix(where))
style <- rep_len(style, nrow(where))
if (length(where) > 0)
x[where] <- sprintf('<div style=\'%s\'>%s</div>',
gsub(';*$', ';', style), x[where])
x
}
library('htmlTable')
htmlTable(inject_div(head(cars), cbind(2,2)))
htmlTable(inject_div(head(cars), where = c(2,2,2,1,5,2),
## equivalently
# where = rbind(c(2,2), c(2,1), c(5,2))
style = c('background-color: red; color: white;',
'border: solid 1px;',
'font-weight: 900; color: blue;')))