Skip to content

Instantly share code, notes, and snippets.

@cpsievert
Created March 22, 2016 05:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cpsievert/2b291f20e5c90ac6ba6e to your computer and use it in GitHub Desktop.
Save cpsievert/2b291f20e5c90ac6ba6e to your computer and use it in GitHub Desktop.
library(shiny)
library(DT)
library(plotly)
ui <- fluidPage(
title = 'Select Table Rows',
h1('A Client-side Table'),
fluidRow(
column(6, DT::dataTableOutput('x1')),
column(6, plotlyOutput('x2', height = 500))
),
hr(),
h1('A Server-side Table'),
fluidRow(
column(9, DT::dataTableOutput('x3')),
column(3, verbatimTextOutput('x4'))
)
)
server <- function(input, output) {
output$x1 <- DT::renderDataTable(cars, server = FALSE)
# highlight selected rows in the scatterplot
output$x2 <- renderPlotly({
p <- plot_ly(cars, x = speed, y = dist, mode = "markers",
marker = list(opacity = 0.2, color = "black"))
s <- input$x1_rows_selected
if (length(s)) {
p <- p %>%
add_trace(data = cars[s, , drop = FALSE],
x = speed, y = dist, mode = "markers",
marker = list(opacity = 1, color = "black")) %>%
layout(showlegend = FALSE)
}
p
})
# server-side processing
mtcars2 <- mtcars[, 1:8]
output$x3 <- DT::renderDataTable(mtcars2, server = TRUE)
# print the selected indices
output$x4 <- renderPrint({
s <- input$x3_rows_selected
if (length(s)) {
cat('These rows were selected:\n\n')
cat(s, sep = ', ')
}
})
}
shinyApp(ui, server)
@zhanxw
Copy link

zhanxw commented Oct 3, 2023

library(shiny)
library(DT)
library(plotly)

ui <- fluidPage(
  
  title = 'Select Table Rows',
  
  h1('A Client-side Table'),
  
  fluidRow(
    column(6, DT::dataTableOutput('x1')),
    column(6, plotlyOutput('x2', height = 500))
  ),
  
  hr(),
  
  h1('A Server-side Table'),
  
  fluidRow(
    column(9, DT::dataTableOutput('x3')),
    column(3, verbatimTextOutput('x4'))
  )
  
)

server <- function(input, output) {
  
  output$x1 <- DT::renderDataTable(cars, server = FALSE)
  
  # highlight selected rows in the scatterplot
  output$x2 <- renderPlotly({
    p <- plot_ly(cars, x = ~speed, y = ~dist, mode = "markers", 
                 marker = list(opacity = 0.2, color = "black"), type = "scatter")
    s <- input$x1_rows_selected
    if (length(s)) {
      p <- p %>%
        add_trace(data = cars[s, , drop = FALSE],
                  x = ~speed, y = ~dist, mode = "markers",
                  marker = list(opacity = 1, color = "black")) %>%
        layout(showlegend = FALSE)
    }
    p
  })
  
  # server-side processing
  mtcars2 <- mtcars[, 1:8]
  output$x3 <- DT::renderDataTable(mtcars2, server = TRUE)
  
  # print the selected indices
  output$x4 <- renderPrint({
    s <- input$x3_rows_selected
    if (length(s)) {
      cat('These rows were selected:\n\n')
      cat(s, sep = ', ')
    }
  })
  
}

shinyApp(ui, server)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment