【问题标题】:How can I change color of text on basis of ifelse condition in R shiny?如何根据 R Shiny 中的 ifelse 条件更改文本颜色?
【发布时间】:2021-06-08 11:10:30
【问题描述】:

我正在尝试使用以下代码。

library(shiny)

app <- shinyApp(
  ui = fluidPage(
    
    DT::dataTableOutput("mydatatable")
  ),
  
  
  server =  shinyServer(function(input, output, session) {
    
    mycars <- reactive({ head(mtcars)})
    output$mydatatable = DT::renderDataTable(mycars(), selection = 'single',  
                                             rownames = FALSE, options = list(dom = 't'))
    selected_row <- reactiveVal(value = NULL)
    observeEvent(input$mydatatable_rows_selected,{
      selected_row(input$mydatatable_rows_selected)
    })
    
    observeEvent(selected_row(),
                 {
                   showModal(modalDialog(
                     title = "You have selected a row!",
                     ifelse(
                       mycars()$mpg[selected_row()] > 21, 
                       tags$div(HTML(paste('cyl = ', tags$span(style = "color:red", mycars()$cyl[selected_row()]), sep = ""))),
                       tags$div(HTML(paste('cyl = ', tags$span(style = "color:blue", mycars()$cyl[selected_row()]), sep = "")))
                     )
                   ))
                 })
  })
)

app

如果“mpg”值大于 21,我正在尝试将“cyl”值的颜色更改为红色,否则“cyl”值将以蓝色打印。

我尝试了一些 html 代码但失败了。

谢谢!

【问题讨论】:

    标签: html r shiny colors


    【解决方案1】:

    为此,数据框不必是响应式的,因此我在此处删除了该部分。利用formatStyle 功能:

    app <- shinyApp(
      ui = fluidPage(
        
        DT::dataTableOutput("mydatatable")
      ),
      
      
      server =  shinyServer(function(input, output, session) {
        
        mycars <- mtcars
        output$mydatatable = DT::renderDataTable(datatable(mycars) %>% 
                                                   formatStyle('cyl', 'mpg',
                                                               color = styleInterval(21.001, c('blue', 'red'))),
                                                               selection = 'single',  
                                                 rownames = FALSE, options = list(dom = 't'))
      })
    )
    
    
    app
    

    【讨论】:

    • 我给出的代码仅用于示例目的。我需要在选择表格的一行时在弹出窗口中显示颜色变化,而不是在实际表格中,所以我使用了 showModal() 函数。
    猜你喜欢
    • 2021-01-09
    • 1970-01-01
    • 2022-07-21
    • 2014-10-22
    • 2018-06-19
    • 2020-10-07
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    相关资源
    最近更新 更多