Reactive formattable in shiny ?

How can I use formattable with reactive tables ?

Here's a reproducible example :

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 ?

Answer from MrFlick (https://stackoverflow.com/questions/56798734/reactive-formattable-in-shiny) :

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"))))
    )
  })

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.