Skip to content

Commit

Permalink
solving exercises chapther 16 (#101)
Browse files Browse the repository at this point in the history
  • Loading branch information
AngelFelizR committed Apr 10, 2024
1 parent 0a2ebf7 commit d8e9514
Show file tree
Hide file tree
Showing 3 changed files with 92 additions and 0 deletions.
29 changes: 29 additions & 0 deletions examples/16-escaping_the_graph/16.3.4-exercises/01-exercise.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@

# Provide a server function that draws a histogram of 100 random numbers
# from a normal distribution when normal is clicked, and 100 random uniforms.

library(shiny)

ui <- fluidPage(
actionButton("rnorm", "Normal"),
actionButton("runif", "Uniform"),
plotOutput("plot")
)

server <- function(input, output, session) {

values <- reactiveVal(vector(mode = "numeric"))

observeEvent(input$rnorm, values(rnorm(100)))

observeEvent(input$runif, values(runif(100)))

output$plot <- renderPlot({
req(input$rnorm | input$runif)
hist(values())
})
}

shinyApp(ui, server)

# source: https://mastering-shiny-solutions.netlify.app/escaping-the-graph
28 changes: 28 additions & 0 deletions examples/16-escaping_the_graph/16.3.4-exercises/02-exercise.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@

# Modify your code from above for to work with this UI:

library(shiny)

ui <- fluidPage(
selectInput("type", "type", c("Normal", "Uniform")),
actionButton("go", "go"),
plotOutput("plot")
)

server <- function(input, output, session) {

values <- reactiveVal(vector(mode = "numeric"))

observeEvent(input$go, {
if(input$type == "Normal") values(rnorm(100)) else values(runif(100))
})

output$plot <- renderPlot({
req(input$go)
hist(values())
})
}

shinyApp(ui, server)

# source: https://mastering-shiny-solutions.netlify.app/escaping-the-graph
35 changes: 35 additions & 0 deletions examples/16-escaping_the_graph/16.3.4-exercises/03-exercise.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@

# Rewrite your code from the previous answer to eliminate the use of
# observe()/observeEvent() and only use reactive().
# Why can you do that for the second UI but not the first?

# Now we just need to track the event go.

library(shiny)

ui <- fluidPage(
selectInput("type", "type", c("Normal", "Uniform")),
actionButton("go", "go"),
plotOutput("plot")
)

server <- function(input, output, session) {

values <- reactive({
if(input$go == 0) return(NULL)
if(input$type == "Normal"){
rnorm(100)
}else{
runif(100)
}
})

output$plot <- renderPlot({
if(is.null(values())) return(NULL)
hist(values())
})
}

shinyApp(ui, server)

# source: https://mastering-shiny-solutions.netlify.app/escaping-the-graph

0 comments on commit d8e9514

Please sign in to comment.