Using input$ to call the dataset

Viewed 53

Suppose I have 2 columns in my dataset, and I want to output out a histogram and summary depending on which column we are on, currently I have 2 if statements per output checking what the input is equal to.

ui <- fluidPage(
  titlePanel("First iteration"),
  sidebarLayout(
    sidebarPanel("Sidebar Panel",
    selectInput("typetoshow", "Choose what you want to display", 
                choices = c("pts", "upts"))             
                 ),
    mainPanel("main panel",
              plotOutput("hist"),
              verbatimTextOutput("sum")
              )
  )
)

server <- function(input, output){
  output$hist <- renderPlot({
    if (input$typetoshow == "pts"){
      hist(data$pts)
    }
    if (input$typetoshow == "upts"){
      hist(data$upts)
    }
  })
  output$sum <- renderPrint({
    if (input$typetoshow == "pts"){
      summary(data$pts)
    }
    if (input$typetoshow == "upts"){
     summary(data$upts)
    }
  })
}

I tried doing

hist(data$input$typetoshow)

But it is giving me an error saying 'x must be numeric' in the histogram and shows NULL for the output summary, is there any way to do this without making many if statements? I am going to be dealing with 10+ columns at one point so I want the code to be neat.

2 Answers

We can use req at the top and then use [[ to subset the dataset column based on the value from 'input$typetoshow'

server <- function(input, output){
  output$hist <- renderPlot({
    req(input$typetoshow)
    
    
      hist(data[[input$typetoshow]])
   
  })
  output$sum <- renderPrint({
       req(input$typetoshow)
    
      summary(data[[input$typetoshow]])
    
  })

You can make it simpler with dplyr::select:

server <- function(input, output){
  output$hist <- renderPlot({
    hist(unlist(dplyr::select(data, input$typetoshow)))
  })
  output$sum <- renderPrint({
    summary(dplyr::select(data, input$typetoshow))

    })
}
Related