library(shiny)
<- fluidPage(
ui sliderInput("blah", "blah again", min = 0, max = 10, value = 5)
)
<- function(input, output) {
server
}
shinyApp(ui = ui, server = server)
Shiny Code example answers
Here’re solutions to the challenges in the lectures
Lecture 1 examples
01_template.R
Here we add a slider input, note that a min
, max
and value
argument is required
02_rnom_example.R
Here we add a radio button and a numeric input to control a plot
library(shiny)
<- fluidPage(
ui sidebarLayout(
sidebarPanel(
radioButtons(inputId="radio",label="Radio Buttons:",
choices=list("red"="red","blue"="blue")),
numericInput(inputId="numeric",label="Data",value=1)
),mainPanel(
plotOutput("distPlot")
)
)
)
<- function(input, output) {
server $distPlot <- renderPlot({
outputset.seed(1)
<-rnorm(input$numeric)
x<-input$radio
colourplot(x,type="o",col=colour)
})
}
shinyApp(ui = ui, server = server)
03_kmeansexample.R
This solution uses a more modern style with cards. I also added another row.
I find it simpler to lay things out with cards, and the modern bslid
driven approach makes the code simpler for me, but both styles are perfectly valid!
# 01-kmeans-app
palette(c("#E41A1C", "#377EB8", "#4DAF4A", "#984EA3",
"#FF7F00", "#FFFF33", "#A65628", "#F781BF", "#999999"))
library(shiny)
library(ggplot2)
library(bslib)
# UI logic
<- page_sidebar(
ui title = "mtcars k-means clustering",
sidebar = sidebar(
selectInput('xcol', 'X Variable', names(mtcars)),
selectInput('ycol', 'Y Variable', names(mtcars),
selected = names(mtcars)[[2]]),
numericInput('clusters', 'Cluster count', 3,
min = 1, max = 9)
),layout_columns(
card(
card_header("A dynamically rendered plot"),
plotOutput('plot1')
),card(
card_header("Another random plot"),
plotOutput('plot2')
)
),card(
card_header("Heres a new row!"),
"We can just have some text too!"
)
)
# Server logic
<- function(input, output, session) {
server $plot1 <- renderPlot({
output# filter mtcars to selected variables
<- mtcars[, c(input$xcol, input$ycol)]
data # cluster data
<- kmeans(data, input$clusters)
clusters # make plot
par(mar = c(5.1, 4.1, 0, 1))
plot(data,
col = clusters$cluster,
pch = 20, cex = 3)
points(clusters$centers, pch = 4, cex = 4, lwd = 4)
})
$plot2 <- renderPlot({
output# make plot
|>
iris ggplot(aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point()
})
}
shinyApp(ui, server)
Lecture 2 examples
Observe event
library(shiny)
<- fluidPage(
ui sliderInput(inputId = "num",
label = "Choose a number",
min = 1, max = 100, value = 25),
actionButton(inputId = "go",label = "Action!"),
# Add the output to the ui
verbatimTextOutput("print")
)
<- function(input, output) {
server
# observe responds to the print button
# but not the slider
observeEvent(input$go, {
# Add an output with a render function
$print <- renderPrint(print(as.numeric(input$num)))
output
})
}
shinyApp(ui = ui, server = server)