Home > Mobile >  How to create datatable using input Shiny R
How to create datatable using input Shiny R

Time:10-02

so I want to make a data table in Shiny that displays only the number of rows that the user inputs. The only other input is which dataset the user wants to see (iris, diamond, or storms). But I can not figure out how to make the table so that it will let you switch between datasets and change the number of rows displayed, I can only do one or the other. I would really appreciate some help. I am really new to R so i'm sorry if this is a simple question. I've looked at similar questions and still can't figure it out. Thank you.(I also have a summary that is printed too but that works fine its just the table that is a problem).

ui <- fluidPage(
  selectInput("dataset", "Choose Dataset", choices = c("iris", "storms", "diamonds")), # 3 dataset options for user to pick from
  numericInput("num", "Row Number To Display", value = 0, min = 0, max = 100), # row number selection
  verbatimTextOutput("summary"),
  dataTableOutput("table") 
)

server <- function(input, output, session) {
  output$summary <- renderPrint({
    dataset <- get(input$dataset)
    summary(dataset)
  })
  
  output$table <- renderDataTable({
    dataset <- get(input$dataset)
    options = list(pageLength = input$num)
    dataset
  })
}

shinyApp(ui, server)

CodePudding user response:

Subset the table to be displayed by input$num.

output$table <- renderDataTable({
    dataset <- get(input$dataset)
    dataset[seq_len(input$num), ]
})

Complete Code -

library(shiny)

ui <- fluidPage(
  selectInput("dataset", "Choose Dataset", choices = c("iris", "storms", "diamonds")), # 3 dataset options for user to pick from
  numericInput("num", "Row Number To Display", value = 0, min = 0, max = 100), # row number selection
  verbatimTextOutput("summary"),
  dataTableOutput("table") 
)

server <- function(input, output, session) {
  
  
  output$summary <- renderPrint({
    dataset <- get(input$dataset)
    summary(dataset)
  })
  
  output$table <- renderDataTable({
    dataset <- get(input$dataset)
    dataset[seq_len(input$num), ]
  })
}

shinyApp(ui, server)

enter image description here

  • Related