我有一个R矩阵我想在浏览器中打开一个html表(可能使用htmlwidgets包吗?)。
还有第二个匹配矩阵,我想将其单元格的内容添加为浏览器表格中各个单元格的翻转工具提示。
是否存在将工具提示矩阵传递到表格的现有方法,在工具提示的相应on.mouseover操作中自动包装每个单元格的内容?
以下是创建源对象的一些代码,包含值和标签矩阵,分别形成单元格内容和鼠标悬停内容。
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= size, size = 1, prob = .5), nrow = ncol, byrow = T)
myObj = list(values = values, labels = labels, free = free)
想要一个函数打开一个ncol×ncol html表,使用“values”来填充每个单元格,on.mouseover,工具提示显示对应于该单元格的标签。
对于额外的点,使用自由矩阵的内容为值着色,FALSE值为红色,TRUE为绿色。
答案 0 :(得分:3)
以下是如何实现此效果的简单示例。我试图保持简单,使其更清晰。我们可以轻松添加更多高级功能和样式。我为奖励积分添加了一些造型。
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
)
)