首页 > 解决方案 > R:如何在 rhandsontable 中为单个单元格着色

问题描述

我有一个数据框(color_cells)保存数据框的单元格的列和行数,这些单元格应该在 rhandsontable 中着色。如何将此信息传递给 renderRHandsontable 中的渲染器?

library(shiny)
library(rhandsontable)

ui <- fluidPage(
  rHandsontableOutput('hot')
)

server <- function(input, output, session) {
  
  color_cells <<- data.frame(col=c(1,2,3),row=c(2,4,5))
  
  output$hot <- renderRHandsontable({
    rhandsontable(mtcars, readOnly = TRUE, width = 750, height = 300) %>%
      hot_cols(renderer = myrenderer)
  })
  
  
  myrenderer <- "function (instance, td, row, col, prop, value, cellProperties) {

  Handsontable.renderers.TextRenderer.apply(this, arguments);

  for ( i in 1:length(color_cells$row) ) {
    r <- color_cells[i,'row']
    c <- color_cells[i,'col']
    if (col == c & row == r ) {  
      td.style.background = 'pink';
      }
    }
  }"
}

shinyApp(ui = ui, server = server)

标签: rrendererrhandsontable

解决方案


这里有一些可以尝试的东西 - 让我知道这是否有效。

调用时rhandsontable包含两个自定义参数,它们将包含表示要突出显示的列和行的向量color_cells

在您的自定义渲染器中,从存储在 params 中的这两个向量创建数组。然后,如果列和行与参数匹配,您可以设置背景颜色。

server <- function(input, output, session) {
  
  color_cells <<- data.frame(col=c(1,2,3),row=c(2,4,5))
  
  output$hot <- renderRHandsontable({
    rhandsontable(mtcars, 
                  col_highlight = color_cells$col - 1,
                  row_highlight = color_cells$row - 1,
                  readOnly = TRUE, 
                  width = 750, 
                  height = 300) %>%
      hot_cols(renderer = myrenderer)
  })

  myrenderer <- "function(instance, td, row, col, prop, value, cellProperties) {
                Handsontable.renderers.TextRenderer.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]
                    
                    for (i = 0; i < hcols.length; i++) { 
                        if (hcols[i] == col && hrows[i] == row) {
                            td.style.background = 'pink';
                        }
                    }
                }
  }"      
}

推荐阅读