MLEN
MLEN

Reputation: 2561

Possible to only show first and last X rows in R Shiny

Is it possible somehow to use shiny renderdatatable to only show the first and last row? Which is changed if the table is ordered.

For this example

if (interactive()) {
  shinyApp(
    ui = fluidPage(
      fluidRow(
        column(12,
               dataTableOutput('table')
        )
      )
    ),
    server = function(input, output) {
      output$table <- renderDataTable(data.frame(A = 1:20, B = 20:1),
                                      options = list(
                                        pageLength = 10
                                      )
      )
    }
  )
}

The desired output output would be

    A  B
1   1 20
20 20  1

and if the user orders by B instead

    A  B
1  20 1
20 1  20

Upvotes: 0

Views: 1249

Answers (1)

Ryan Morton
Ryan Morton

Reputation: 2695

You can manipulate your data table within a reactive space to create any behavior you want. Here I take the head and tail of the df object after it has been ordered/reordered:

if (interactive()) {
  library(shiny)
  shinyApp(
    ui = fluidPage(
      fluidRow(
        column(3,
               selectInput("ordering", "How to order", choices = c("A", "B"), selected = "A")),
        column(9,
               dataTableOutput('table')
        )
      )
    ),
    server = function(input, output) {
      output$table <- renderDataTable({ 
        df <- data.frame(A = 1:20, B = 20:1)

        df <- df[order(df[[input$ordering]]), ]

        df_new <- rbind(head(df,1), tail(df,1))
        df_new
        },
        options = list(pageLength = 10))
    }
  )
}

Upvotes: 1

Related Questions