Reactive formattable in shiny?

好久不见. 提交于 2019-12-11 14:56:00

问题


How can I use formattable to color some values in reactive tables ?

Here's a reproducible example : I would like to color p-values in red if they are inferior to 0.05 in the reactive results table I created.

library(DT)
library(shiny)
library(shinydashboard)
library(formattable)


ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(    
    selectizeInput("v.dependent", "", choices = names(mtcars), 
                                      selected = "mpg", multiple = FALSE),
    selectizeInput("predictor", "", choices = names(mtcars), 
                                      selected = "disp", 
                                      multiple = TRUE)),
  dashboardBody(
    tabsetPanel(
      tabPanel("test with mtcars",
               box(formattableOutput("tab"))
      )
    )
  )
)

server <- function(input, output) {

  dep.var <- reactive({
    out <- input$v.dependent
    out
  })

  ind.var <- reactive({
    out <- input$predictor
    out
  })

  var.selected <- reactive({
    out <- append(ind.var(), dep.var(), 0)
    out
  })

  user.selection <- reactive({
    mtcars[, names(mtcars) %in% var.selected()]
  })

  lmod <- reactive({
    lm(as.formula(paste(input$v.dependent, "~", paste(input$predictor, collapse = "+"))), data = user.selection())
  })

  output$tab <- renderFormattable({
    tmp <- summary(lmod())$coefficients
    colnames(tmp) <- c("Coefficients", "SD", "t statistic", "Pvalue")
    tmp <- signif(x = tmp, digits = 3)
    tmp <- formattable(tmp, list(Pvalue = formatter("span", 
                         style = x ~ style(color = ifelse(x < 0.05, style(color = "red", "black")))
      )))
  })

}


shinyApp(ui, server)

I know how to do with "static" tables but when I try with this code, I've got the error :

Warning: Error in formatC: 'format' must be one of {"f","e","E","g","G", "fg", "s"}

Any idea how to solve it ?


回答1:


You're using the syntax for formattable.data.table but in your case tmp is a matrix which behaves differently. It seems you want it to be a data.frame so you can cast it yourself. Also, you seem to have some problems with setting the color in your ifelse. This seems to do what you want

output$tab <- renderFormattable({
    tmp <- summary(lmod())$coefficients
    colnames(tmp) <- c("Coefficients", "SD", "t statistic", "Pvalue")
    tmp <- signif(x = tmp, digits = 3)
    tmp <- as.data.frame(tmp)
    tmp <- formattable(tmp, list(
      Pvalue = formatter("span", style = x ~ style(color = ifelse(x < 0.05, "red", "black"))))
    )
  })


来源:https://stackoverflow.com/questions/56798734/reactive-formattable-in-shiny

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!