Search code examples
rshinyshinydashboardshinyapps

R shiny dashboard infobox with a dataset input


I am new to and shiny and suspect that I am stuck with a simple problem.

I want 2 infoboxes which show me in one the maximum amount over all categories and in the second infobox only the category with the most amount and its total amount.

I have tried a lot of things but nothing brought me success.

## app.R ##
library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(

    uiOutput("info_box1"),
    uiOutput("info_box2"),
    uiOutput("rawdata")
  )
)

set.seed(24)
mydf <- data.frame(Type = sample(LETTERS[1:5], 30, replace = TRUE),
                   Amount = sample(10:200, 30, replace = TRUE), 
                   stringsAsFactors= FALSE, check.names = FALSE)


server <- function(input, output) {

  output$info_box1 <- renderUI({
    infoBox("Amount in Total here", input$ "???")
  })

  output$info_box2 <- renderUI({
    infoBox("Class with the hightest amount and amount in total of that class", "input$ function needed?")
  })

  output$rawdata = renderTable({
    mydf
  })


}

# Run the application 
shinyApp(ui = ui, server = server)

Could someone please show me how to do this?

Thanks a lot. Appreciate your help.


Solution

  • You should use approriate functions, see here : https://rstudio.github.io/shinydashboard/structure.html

    app.R

    library(shiny)
    library(shinydashboard)
    library(dplyr)
    
    ui <- dashboardPage(
      dashboardHeader(),
      dashboardSidebar(),
      dashboardBody(
    
        infoBoxOutput("info_box1"),
        infoBoxOutput("info_box2"),
        tableOutput("rawdata")
      )
    )
    
    set.seed(24)
    mydf <- data.frame(Type = sample(LETTERS[1:5], 30, replace = TRUE),
                       Amount = sample(10:200, 30, replace = TRUE), 
                       stringsAsFactors= FALSE, check.names = FALSE)
    
    
    server <- function(input, output) {
    
      output$info_box1 <- renderInfoBox({
        infoBox("Amount in Total here", sum(mydf$Amount))
      })
    
      output$info_box2 <- renderInfoBox({
    df_output <- mydf %>% group_by(Type) %>% tally()
        infoBox("Class with the hightest amount and amount in total of that class", paste(df_output$Type[df_output$n == max(df_output$n)],max(df_output$n))  )
      })
    
      output$rawdata = renderTable({
        mydf
      })
    
    
    }
    
    # Run the application 
    shinyApp(ui = ui, server = server)