| 1 |
library(shiny) |
| 2 |
library(bslib) |
| 3 |
|
| 4 |
# Define UI for random distribution app ---- |
| 5 |
# Sidebar layout with input and output definitions ---- |
| 6 |
ui <- page_sidebar( |
| 7 |
|
| 8 |
# App title ---- |
| 9 |
title = "Tabsets", |
| 10 |
|
| 11 |
# Sidebar panel for inputs ---- |
| 12 |
sidebar = sidebar( |
| 13 |
|
| 14 |
# Input: Select the random distribution type ---- |
| 15 |
radioButtons( |
| 16 |
"dist", |
| 17 |
"Distribution type:", |
| 18 |
c( |
| 19 |
"Normal" = "norm", |
| 20 |
"Uniform" = "unif", |
| 21 |
"Log-normal" = "lnorm", |
| 22 |
"Exponential" = "exp" |
| 23 |
) |
| 24 |
), |
| 25 |
# br() element to introduce extra vertical spacing ---- |
| 26 |
br(), |
| 27 |
# Input: Slider for the number of observations to generate ---- |
| 28 |
sliderInput( |
| 29 |
"n", |
| 30 |
"Number of observations:", |
| 31 |
value = 500, |
| 32 |
min = 1, |
| 33 |
max = 1000 |
| 34 |
) |
| 35 |
), |
| 36 |
|
| 37 |
# Main panel for displaying outputs ---- |
| 38 |
# Output: A tabset that combines three panels ---- |
| 39 |
navset_card_underline( |
| 40 |
# Panel with plot ---- |
| 41 |
nav_panel("Plot", plotOutput("plot")), |
| 42 |
|
| 43 |
# Panel with summary ---- |
| 44 |
nav_panel("Summary", verbatimTextOutput("summary")), |
| 45 |
|
| 46 |
# Panel with table ---- |
| 47 |
nav_panel("Table", tableOutput("table")) |
| 48 |
) |
| 49 |
) |
| 50 |
|
| 51 |
# Define server logic for random distribution app ---- |
| 52 |
server <- function(input, output) { |
| 53 |
|
| 54 |
# Reactive expression to generate the requested distribution ---- |
| 55 |
# This is called whenever the inputs change. The output functions |
| 56 |
# defined below then use the value computed from this expression |
| 57 |
d <- reactive({ |
| 58 |
dist <- switch( |
| 59 |
input$dist, |
| 60 |
norm = rnorm, |
| 61 |
unif = runif, |
| 62 |
lnorm = rlnorm, |
| 63 |
exp = rexp, |
| 64 |
rnorm |
| 65 |
) |
| 66 |
|
| 67 |
dist(input$n) |
| 68 |
}) |
| 69 |
|
| 70 |
# Generate a plot of the data ---- |
| 71 |
# Also uses the inputs to build the plot label. Note that the |
| 72 |
# dependencies on the inputs and the data reactive expression are |
| 73 |
# both tracked, and all expressions are called in the sequence |
| 74 |
# implied by the dependency graph. |
| 75 |
output$plot <- renderPlot({ |
| 76 |
dist <- input$dist |
| 77 |
n <- input$n |
| 78 |
|
| 79 |
hist( |
| 80 |
d(), |
| 81 |
main = paste("r", dist, "(", n, ")", sep = ""), |
| 82 |
col = "#75AADB", |
| 83 |
border = "white" |
| 84 |
) |
| 85 |
}) |
| 86 |
|
| 87 |
# Generate a summary of the data ---- |
| 88 |
output$summary <- renderPrint({ |
| 89 |
summary(d()) |
| 90 |
}) |
| 91 |
|
| 92 |
# Generate an HTML table view of the data ---- |
| 93 |
output$table <- renderTable({ |
| 94 |
d() |
| 95 |
}) |
| 96 |
} |
| 97 |
|
| 98 |
# Create Shiny app ---- |
| 99 |
shinyApp(ui, server) |