【问题标题】:R Rhansontable - Color Specific Cells Conditionally On Other TableR Rhansontable - 有条件地在其他表上的颜色特定单元格
【发布时间】:2020-03-25 05:37:37
【问题描述】:

这是我在 SO 上的第一篇帖子,如果我的帖子不完全符合规则,请多多包涵。尽管我会尽力清楚地描述我的问题,但我已经检查过的资源并提供了一个可重复的示例。

首先,让我解释一下问题:我想用不同颜色(红色和绿色)根据来自另一个表的条件(用布尔值填充的相同 nb 列/行,其中 TRUE=green,FALSE=red)。

假设我想从以下两个表开始:

DF = data.frame(val = 1:3, big = LETTERS[1:3])

DF_condition = data.frame(val = c(TRUE, FALSE,FALSE), big = c(FALSE,TRUE,FALSE))

我希望 (1,1)(2,2) 处的单元格,即另一个表设置为 TRUE 为绿色,所有其他单元格为红色。

我查看了 SO(和其他)中的多个其他帖子,例如:

但是,它们都没有解决我的问题。事实上,我面临以下三个主要问题:

  1. 我不是要突出显示整行/列,而是只突出特定单元格
  2. 条件格式应该使用另一个表中的条件来完成
  3. 我的数据库有数十万行和大约 20 列(如果可能,我希望使用矢量化方法,而不是通过列/行循环)

由于我不熟悉在 rhandsontable 中使用的 JScript,所以我有点卡住了。

请在下面找到一个最小的可复制示例:

ui <- shinyUI(bootstrapPage(
  rHandsontableOutput("hot")
))

server <- shinyServer(function(input, output) {
  output$hot <- renderRHandsontable({
    DF = data.frame(val = 1:3, big = LETTERS[1:3])
    DF_condition = data.frame(val = c(TRUE, FALSE,FALSE), big = c(FALSE,TRUE,FALSE))
    col_highlight = c(1,2)
    row_highlight = c(1,3)

    rhandsontable(DF, col_highlight = col_highlight-1, row_highlight = row_highlight-1) %>%
      hot_cols(renderer = "
               function(instance, td, row, col, prop, value, cellProperties) {
               Handsontable.renderers.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) && hrows.includes(row)) td.style.background = 'red';
               }")
    })
})
shinyApp(ui, server)

突出显示前两列和前两行,而我只需要单元格(1,1)(2,2)

非常感谢您的热心帮助。

【问题讨论】:

  • 更新问题看看有没有人可以帮忙?

标签: r shiny rhandsontable


【解决方案1】:

您当前正在检查列是否在数组[1,2] 中以及行是否在数组[1, 2] 中。所有四个组合(1,1)(1,2)(2,1)(2,2) 都满足此要求,这就是所有这些单元格都被涂成红色的原因。相反,您要确保如果列是数组[1,2] 的第一个元素,那么行也应该是数组[1,2] 的第一个元素,而不是第二个元素。
我不是 JavaScript 专家,但这样的事情可能会奏效:

if (instance.params && hcols.includes(col) && hrows.includes(row) && (hcols.indexOf(col) == hrows.indexOf(row))) {
td.style.background = 'red';
}

【讨论】:

    猜你喜欢
    • 2016-07-01
    • 1970-01-01
    • 2015-09-14
    • 2014-05-03
    • 2014-12-23
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多