Search code examples
rshinydashboardflextable

Trouble with table output in Shiny


This is my data set

enter image description here

and i want to filter on product in Shiny with flextable and get something like this :

enter image description here

this is my code :

library(shiny)

my_data = data.frame(product = rep(c("auto", "boat"),each=2),
                  year = c("2009", "2011", "2005", "2019"),
                  price = c("10 000", "20 000", "7 000", "60 000"),
                  speed = c("220", "250", "70", "140"))


ui <- fluidPage(
  selectInput("product", "", choices = my_data$product),
  tableOutput("tbl")
)

server <- function(input, output, session) {
  output$tbl <- renderTable( {
    out <- subset(my_data, product ==input$product)
    library(flextable)
    flextable(out) # i got error
  })
}

shinyApp(ui, server)

but i got this error : cannot coerce class ‘"flextable"’ to a data.frame

How can we fix it ? Some help would be appreciated


Solution

  • You cannot use renderTable with a flextable object. See ?renderTable:

    expr: An expression that returns an R object that can be used with xtable::xtable().

    Here you can find a tutorial on how to use flextable within a shiny app.

    Please check the following:

    library(shiny)
    library(flextable)
    
    my_data = data.frame(product = rep(c("auto", "boat"),each=2),
                         year = c("2009", "2011", "2005", "2019"),
                         price = c("10 000", "20 000", "7 000", "60 000"),
                         speed = c("220", "250", "70", "140"))
    
    
    ui <- fluidPage(
      selectInput("product", "", choices = my_data$product),
      uiOutput("tbl")
    )
    
    server <- function(input, output, session) {
      output$tbl <- renderUI( {
        out <- subset(my_data, product ==input$product)
        library(flextable)
        htmltools_value((flextable(out)))
      })
    }
    
    shinyApp(ui, server)