如何在 R Shiny 中对数据帧进行条件格式设置? [英] How to have conditional formatting of data frames in R Shiny?

查看:23
本文介绍了如何在 R Shiny 中对数据帧进行条件格式设置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Excel,您可以轻松地对单元格应用条件格式:

With Excel, you can easily apply conditional formatting over cells:

你有没有机会用 Shiny 做这样的事情?我已经阅读了 教程,但这显然没有涵盖.

Is there any chance you can do something like this with Shiny? I've gone through the tutorials, but this apparently is not covered.

例如,我想有条件地为 runExample("02_text") 中的 perm 行着色:

For instance, I'd like to conditionally colour the perm row in runExample("02_text"):

推荐答案

您可以使用 jQuery 对表格进行条件格式化.

You can conditionnal formatting your table using jQuery.

例如:

library(shiny)
library(datasets)

script <- "$('tbody tr td:nth-child(5)').each(function() {

              var cellValue = $(this).text();

              if (cellValue > 50) {
                $(this).css('background-color', '#0c0');
              }
              else if (cellValue <= 50) {
                $(this).css('background-color', '#f00');
              }
            })"

runApp(list(
  ui = basicPage(
    tags$head(tags$script(HTML('Shiny.addCustomMessageHandler("jsCode", function(message) { eval(message.value); });'))),
    tableOutput("view")
  ),
  server = function(input, output, session) {

    session$onFlushed(function() {
      session$sendCustomMessage(type='jsCode', list(value = script))
    })

    output$view <- renderTable({
      head(rock, n = 20)
    })
  }
))

tbody tr td:nth-child(5) 我精确到 nth-child(5) 来循环每个 td 的仅第 5 列(烫发).

In tbody tr td:nth-child(5) I precise nth-child(5) To loop on each td of the 5th column only (perms).

我们需要 session$onFlushed(function() {session$sendCustomMessage(type='jsCode', list(value = script))}) 因为如果你把脚本放在头部,它将在表格输出呈现之前执行,然后什么都不会格式化.

We need session$onFlushed(function() { session$sendCustomMessage(type='jsCode', list(value = script)) }) because if you put the script in the head, it will be executed before the table output rendered and then nothing will be formatting.

如果您想要更多格式,我建议您创建 css 类并使用 addClass :

If you want more formatting I suggest you to create css classes and use addClass :

### In the UI :
tags$head(tags$style(
            ".greenCell {
                background-color: #0c0;
            }

            .redCell {
                background-color: #f00;
            }"))

### In th script
### use .addClass instead of .css(...)

$(this).addClass('greenCell')

这篇关于如何在 R Shiny 中对数据帧进行条件格式设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆