这是一个快速示例,说明如何实现此效果。我试图保持简单以使其更清晰。我们可以轻松添加更高级的功能和样式。我为加分添加了一些样式。
ncol = 4 # typically rank 1:9
n = ncol^2
values = matrix(round(rnorm(n),2), nrow = ncol, byrow = T)
labs = paste0("r", rep(1:ncol, each = ncol), "c", rep(1:ncol, times = ncol))
labels = matrix(labs, nrow = ncol, byrow = T)
free = matrix(rbinom(n= n, size = 1, prob = .5), nrow = ncol, byrow = T)
myObj = list(values = values, labels = labels, free = free)
# use formattable, htmlwidgets, and htmltools
library(formattable)
library(htmltools)
library(htmlwidgets)
# see what formattable gives us
formattable(myObj$values)
# now make each of our cells
# contain information for our tooltip
m_html <- matrix(
mapply(
function(value, label, free){
as.character(tags$span(
"data-toggle"="tooltip",
"title" = paste0(label, ": ", free),
formatC(value, format="f", digits=3)
))
},
myObj$values,
myObj$labels,
myObj$free
),
ncol = 4
)
browsable(
attachDependencies(
tagList(
onRender(
as.htmlwidget(formattable(m_html)),
"
function(el,x){
$(el).find('[data-toggle=\"tooltip\"]').tooltip()
}
"
)
),
shiny::bootstrapLib()
)
)
这是一种非常简单的方法,可以以不同的方式执行上述操作,并添加您建议的样式。
# purrr could ease some of this pain
# but wanted to avoid dependencies
formattable(
matrix(
formatter(
"span",
"data-toggle" = "tooltip",
# use the label and free to add a simple title
# this can be infinitely styled and refined
"title" = mapply(
function(value,label,free) {
paste0(label,": ",free)
},
myObj$values, myObj$label, myObj$free
),
# color the background of cells based on free
"style" = mapply(
function(value,free) {
if(free==1) color = "red"
if(free==0) color = "green"
paste0("display:block; background:",color,";")
},
myObj$values, myObj$free
),
# values will be the text in the cells
x~x
)(myObj$values),
# put back in a matrix of ncol=4
ncol=4
)
)