所以,我正在创建一个闪亮的应用程序,我想在使用rhandsontable生成的表格中为某些行着色。
我正在关注这个非常好的教程:https://jrowen.github.io/rhandsontable/
具体来说,我对这部分感兴趣:
library(rhandsontable)
DF = data.frame(val = 1:10, bool = TRUE, big = LETTERS[1:10],
small = letters[1:10],
dt = seq(from = Sys.Date(), by = "days", length.out = 10),
stringsAsFactors = FALSE)
col_highlight = 2
row_highlight = c(5, 7)
rhandsontable(DF, col_highlight = col_highlight,
row_highlight = row_highlight,
width = 550, height = 300) %>%
hot_cols(renderer = "
function(instance, td, row, col, prop, value, cellProperties) {
Handsontable.TextCell.renderer.apply(this, arguments);
tbl = this.HTMLWidgets.widgets[0]
hcols = tbl.params.col_highlight
hcols = hcols instanceof Array ? hcols : [hcols]
hrows = tbl.params.row_highlight
hrows = hrows instanceof Array ? hrows : [hrows]
if (hcols.includes(col) && hrows.includes(row)) {
td.style.background = 'red';
}
else if (hcols.includes(col)) {
td.style.background = 'lightgreen';
}
else if (hrows.includes(row)) {
td.style.background = 'pink';
}
return td;
}")
此代码适用于RStudio,但不适用于Shiny(表格根本不显示)。网站上有一个解释说,如果在Shiny上使用它,我们应该将该部分添加到代码中:
HTMLWidgets.widgets.filter(function(widget) {
// this should match the table id specified in the shiny app
return widget.name === "hot"
})[0];
但是,由于我对javascript一无所知,所以我觉得这个部分应该去哪里。我尝试了很多东西,包括:
rhandsontable(DF, col_highlight = col_highlight,
row_highlight = row_highlight,
width = 550, height = 300) %>%
hot_cols(renderer = "
function(instance, td, row, col, prop, value, cellProperties) {
Handsontable.TextCell.renderer.apply(this, arguments);
HTMLWidgets.widgets.filter(function(widget) {
// this should match the table id specified in the shiny app
return widget.name === \"hot\"
})[0];
..
但它仍然不正确。
对于熟悉js的人来说,这可能是一个非常基本的问题,但是这样做的正确方法是什么?
答案 0 :(得分:2)
着色列和行的简单示例。
ui <- shinyUI(bootstrapPage(
rHandsontableOutput("hot")
))
server <- shinyServer(function(input, output) {
output$hot <- renderRHandsontable({
DF = data.frame(val = 1:10, big = LETTERS[1:10])
col_highlight = c(0, 1)
row_highlight = c(3)
rhandsontable(DF, col_highlight = col_highlight, row_highlight = row_highlight) %>%
hot_cols(renderer = "
function(instance, td, row, col, prop, value, cellProperties) {
Handsontable.NumericRenderer.apply(this, arguments);
if (instance.params) {
hcols = instance.params.col_highlight
hcols = hcols instanceof Array ? hcols : [hcols]
hrows = instance.params.row_highlight
hrows = hrows instanceof Array ? hrows : [hrows]
}
if (instance.params && hcols.includes(col)) td.style.background = 'red';
if (instance.params && hrows.includes(row)) td.style.background = 'yellow';
}")
})
})
shinyApp(ui, server)
<强>更新强>
@SeGa指出自rhandsontable
版本0.3.6.1以来使用Handsontable.renderers.NumericRenderer.apply(this, arguments);
代替
Handsontable.NumericRenderer.apply(this, arguments);