Wilcar
Wilcar

Reputation: 2513

Select the number of rows to display in a datatable based on a slider input

I am trying to select the number of rows to display in a datable using a slider input.

Here's my app working with a pageLength of 2

library(shiny)
library(DT)

# Dummy data 
dataset <- data.frame(lng = c(-5, -5, -5, -5, -15, -15, -10),
             lat = c(8, 8, 8, 8, 33, 33, 20),
             year = c(2018, 2018, 2018, 2017, 2017, 2017, 2016),
             type = c('A', 'A', 'A', 'A', 'B', 'B', 'A'),
             id =c("1", "1", "1", "1", "2", "2", "3"))


ui <- fluidPage(

  sidebarLayout(
  sidebarPanel(
     sliderInput("rows",
                 "Number of rows",
                 min = 1,
                 max = 50,
                 value = 1)
  ),

 # datable output 
     DT::dataTableOutput(outputId =  "table")
  )
 )
)

 server <- function(input, output) {



        output$table <- DT::renderDataTable(
            dat <- datatable(dataset,
                             options = list(
                               paging =TRUE,
                               pageLength =  2 
                               )
                             )
            )

        }

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

What I tried on server side: 1. First, I tried to use sliderInput$rows as argument of pageLength : pageLength = sliderInput$rows

  1. I also tried on server side :

     server <- function(input, output) {
    
      i <- reactive({sliderInput$rows})
    
      output$table <- DT::renderDataTable(
        dat <- datatable(dataset,
                         options = list(
                           paging =TRUE,
                           pageLength =  i() 
                         )
        )
      )
    
    }
    

Upvotes: 6

Views: 7190

Answers (1)

Wilcar
Wilcar

Reputation: 2513

Based on Aurèle comment, here is my updated server side :

server <- function(input, output) {

    output$table <- DT::renderDataTable(
        dat <- datatable(dataset,
                         options = list(
                           paging =TRUE,
                           pageLength =  input$rows 
                           )
                         )
        )

    }

Upvotes: 11

Related Questions