| 1 |
library(shiny) |
| 2 |
|
| 3 |
# Define UI for dataset viewer app ---- |
| 4 |
ui <- fluidPage( |
| 5 |
|
| 6 |
# App title ---- |
| 7 |
titlePanel("More Widgets"), |
| 8 |
|
| 9 |
# Sidebar layout with input and output definitions ---- |
| 10 |
sidebarLayout( |
| 11 |
|
| 12 |
# Sidebar panel for inputs ---- |
| 13 |
sidebarPanel( |
| 14 |
|
| 15 |
# Input: Select a dataset ---- |
| 16 |
selectInput("dataset", "Choose a dataset:", |
| 17 |
choices = c("rock", "pressure", "cars")), |
| 18 |
|
| 19 |
# Input: Specify the number of observations to view ---- |
| 20 |
numericInput("obs", "Number of observations to view:", 10), |
| 21 |
|
| 22 |
# Include clarifying text ---- |
| 23 |
helpText("Note: while the data view will show only the specified", |
| 24 |
"number of observations, the summary will still be based", |
| 25 |
"on the full dataset."), |
| 26 |
|
| 27 |
# Input: actionButton() to defer the rendering of output ---- |
| 28 |
# until the user explicitly clicks the button (rather than |
| 29 |
# doing it immediately when inputs change). This is useful if |
| 30 |
# the computations required to render output are inordinately |
| 31 |
# time-consuming. |
| 32 |
actionButton("update", "Update View") |
| 33 |
|
| 34 |
), |
| 35 |
|
| 36 |
# Main panel for displaying outputs ---- |
| 37 |
mainPanel( |
| 38 |
|
| 39 |
# Output: Header + summary of distribution ---- |
| 40 |
h4("Summary"), |
| 41 |
verbatimTextOutput("summary"), |
| 42 |
|
| 43 |
# Output: Header + table of distribution ---- |
| 44 |
h4("Observations"), |
| 45 |
tableOutput("view") |
| 46 |
) |
| 47 |
|
| 48 |
) |
| 49 |
) |
| 50 |
|
| 51 |
# Define server logic to summarize and view selected dataset ---- |
| 52 |
server <- function(input, output) { |
| 53 |
|
| 54 |
# Return the requested dataset ---- |
| 55 |
# Note that we use eventReactive() here, which depends on |
| 56 |
# input$update (the action button), so that the output is only |
| 57 |
# updated when the user clicks the button |
| 58 |
datasetInput <- eventReactive(input$update, { |
| 59 |
switch(input$dataset, |
| 60 |
"rock" = rock, |
| 61 |
"pressure" = pressure, |
| 62 |
"cars" = cars) |
| 63 |
}, ignoreNULL = FALSE) |
| 64 |
|
| 65 |
# Generate a summary of the dataset ---- |
| 66 |
output$summary <- renderPrint({ |
| 67 |
dataset <- datasetInput() |
| 68 |
summary(dataset) |
| 69 |
}) |
| 70 |
|
| 71 |
# Show the first "n" observations ---- |
| 72 |
# The use of isolate() is necessary because we don't want the table |
| 73 |
# to update whenever input$obs changes (only when the user clicks |
| 74 |
# the action button) |
| 75 |
output$view <- renderTable({ |
| 76 |
head(datasetInput(), n = isolate(input$obs)) |
| 77 |
}) |
| 78 |
|
| 79 |
} |
| 80 |
|
| 81 |
# Create Shiny app ---- |
| 82 |
shinyApp(ui, server) |