15 Mi primera aplicación ShinyR

Alejandro Reyes

12 de agosto de 2021

15.1 Diapositivas

15.2 Paso 0: Genera un código lineal

library(dslabs)
library(magrittr)
library(ggplot2)
library(tidyverse)
library(ggridges)
data(gapminder)

ymin <- 1960
ymax <- 2016
colorBy <- "continent"
  
gapminder %>%
  filter( country %in% c("Mexico", "South Korea", "Germany") ) %>%
  ggplot( aes( year, life_expectancy, col=get(colorBy), group=country )) +
  geom_point( size=0.3 ) +
  geom_line( ) +
  xlim(c(ymin, ymax)) +
  labs(col=colorBy)

gapminder %>%
  filter( country %in% c("Mexico", "South Korea", "Germany") ) %>%
  ggplot( aes( year, fertility, col=get(colorBy), group=country )) +
  geom_point( size=0.3 ) +
  geom_line( ) +
  xlim(c(ymin, ymax)) +
  labs(col=colorBy)


keep_regions <- gapminder %>%
  filter( country %in% c("Mexico", "South Korea", "Germany") ) %>%
  pull( region ) %>%
  as.character %>%
  unique

gapminder %>%
  mutate( dollars_per_day=gdp/population/365 ) %>%
  filter( year %in% seq(1960, 2010, 10), 
          !is.na(dollars_per_day), 
          region %in% keep_regions ) %>%
  filter( between(year, ymin, ymax) ) %>%
  ggplot( aes( dollars_per_day, factor(year) ) ) +
  scale_x_continuous(trans = "log2")  +
  geom_density_ridges(jittered_points = TRUE) +
  facet_grid( ~region, scales="free")

gapminder %>%
  mutate( dollars_per_day=gdp/population/365 ) %>%
  filter( 
    country %in% c("Mexico", "South Korea", "Germany"), 
    between( year, ymin, ymax) )

15.3 Paso 1: Genera la Shiny app y agrega una primer gráfica

library(shiny)
library(dslabs)
library(magrittr)
library(ggplot2)
library(tidyverse)
library(ggridges)
data(gapminder)

ymin <- 1960
ymax <- 2016
colorBy <- "continent"

ui <- fluidPage(
    # Application title
    titlePanel("Visualización exploratoria de gapminder"),
    # Sidebar for parameters
    sidebarLayout(
        sidebarPanel(),
        mainPanel(
           plotOutput("lifeExpPlot")
        )
    )
)

# Define server logic required to draw a histogram
server <- function(input, output) {
    output$lifeExpPlot <- renderPlot({
        gapminder %>%
            filter( country %in% c("Mexico", "South Korea", "Germany") ) %>%
            ggplot( aes( year, life_expectancy, col=get(colorBy), group=country )) +
            geom_point( size=0.3 ) +
            geom_line( ) +
            xlim(c(ymin, ymax)) +
            labs(col=colorBy)
    })
}

# Run the application 
shinyApp(ui = ui, server = server)

15.4 Paso 2: Agrega una opción para seleccionar datos

library(shiny)
library(dslabs)
library(magrittr)
library(ggplot2)
library(tidyverse)
library(ggridges)
data(gapminder)

ymin <- 1960
ymax <- 2016
colorBy <- "continent"

ui <- fluidPage(
  # Application title
  titlePanel("Visualización exploratoria de gapminder"),
  # Sidebar for parameters
  sidebarLayout(
    sidebarPanel(
      ## Código para seleccionar paises
      selectizeInput( 'countries', label = "Seleccionar paises", 
                      choices = levels(gapminder$country), multiple=TRUE)
    ),
    mainPanel(
      plotOutput("lifeExpPlot")
    )
  )
)

# Define server logic
server <- function(input, output) {
  output$lifeExpPlot <- renderPlot({
    gapminder %>%
      filter( country %in% input$countries ) %>%
      ggplot( aes( year, life_expectancy, col=get(colorBy), group=country )) +
      geom_point( size=0.3 ) +
      geom_line( ) +
      xlim(c(ymin, ymax)) +
      labs(col=colorBy)
  })
}

# Run the application 
shinyApp(ui = ui, server = server)

15.5 Paso 3: Agrega una barra con rangos de valores

library(shiny)
library(dslabs)
library(magrittr)
library(ggplot2)
library(tidyverse)
library(ggridges)
data(gapminder)

colorBy <- "continent"

ui <- fluidPage(
  # Application title
  titlePanel("Visualización exploratoria de gapminder"),
  # Sidebar for parameters
  sidebarLayout(
    sidebarPanel(
      ## Código para seleccionar paises
      selectizeInput( 'countries', label = "Seleccionar paises", 
                      choices = levels(gapminder$country), multiple=TRUE),
      sliderInput( 'ylms', label = h3("Años contemplados"), min = 1960, 
                  max = 2020, value = c(1960, 2016) )
    ),
    mainPanel(
      plotOutput("lifeExpPlot")
    )
  )
)

# Define server logic
server <- function(input, output) {
  output$lifeExpPlot <- renderPlot({
    gapminder %>%
      filter( country %in% input$countries ) %>%
      ggplot( aes( year, life_expectancy, col=get(colorBy), group=country )) +
      geom_point( size=0.3 ) +
      geom_line( ) +
      coord_cartesian(xlim=c(input$ylms[1], input$ylms[2])) +
      labs(col=colorBy)
  })
}

# Run the application 
shinyApp(ui = ui, server = server)

15.6 Paso 4: Agrega botones

library(shiny)
library(dslabs)
library(magrittr)
library(ggplot2)
library(tidyverse)
library(ggridges)
data(gapminder)

ui <- fluidPage(
  # Application title
  titlePanel("Visualización exploratoria de gapminder"),
  # Sidebar for parameters
  sidebarLayout(
    sidebarPanel(
      ## Código para seleccionar paises
      selectizeInput( 'countries', label = h3("Seleccionar paises"), 
                      choices = levels(gapminder$country), multiple=TRUE),
      sliderInput( 'ylms', label = h3("Años contemplados"), min = 1960, 
                   max = 2020, value = c(1960, 2016) ),
      radioButtons( 'colorBy', label=h3("Colorear por"), 
                    choices = c(pais="country", continente="continent"), 
                    selected = "continent" )
    ),
    mainPanel(
      plotOutput("lifeExpPlot")
    )
  )
)

# Define server logic
server <- function(input, output) {
  output$lifeExpPlot <- renderPlot({
    gapminder %>%
      filter( country %in% input$countries ) %>%
      ggplot( aes( year, life_expectancy, col=get(input$colorBy), group=country )) +
      geom_point( size=0.3 ) +
      geom_line( ) +
      coord_cartesian(xlim=c(input$ylms[1], input$ylms[2])) +
      labs(col=input$colorBy)
  })
}

# Run the application 
shinyApp(ui = ui, server = server)

15.7 Paso 5: Agrega algo de texto

library(shiny)
library(dslabs)
library(magrittr)
library(ggplot2)
library(tidyverse)
library(ggridges)
data(gapminder)

ui <- fluidPage(
  # Application title
  titlePanel("Visualización exploratoria de gapminder"),
  # Sidebar for parameters
  sidebarLayout(
    sidebarPanel(
      ## Código para seleccionar paises
      selectizeInput( 'countries', label = h3("Seleccionar paises"), 
                      choices = levels(gapminder$country), multiple=TRUE),
      sliderInput( 'ylms', label = h3("Años contemplados"), min = 1960, 
                   max = 2020, value = c(1960, 2016) ),
      radioButtons( 'colorBy', label=h3("Colorear por"), 
                    choices = c(pais="country", continente="continent"), 
                    selected = "continent" )
    ),
    mainPanel(
      tabsetPanel(
        tabPanel("Esperanza de vida", 
                 plotOutput("lifeExpPlot"),
                 textOutput("plotLegend"))
      )
    )
  )
)

# Define server logic
server <- function(input, output) {
  output$lifeExpPlot <- renderPlot({
    gapminder %>%
      filter( country %in% input$countries ) %>%
      ggplot( aes( year, life_expectancy, col=get(input$colorBy), group=country )) +
      geom_point( size=0.3 ) +
      geom_line( ) +
      coord_cartesian(xlim=c(input$ylms[1], input$ylms[2])) +
      labs(col=input$colorBy)
  })
  output$plotLegend <- renderText({ 
    sprintf("Datos de esperanza de vida del año %d al año %d. Cada color 
    representa un %s. Los siguientes países estan representados en el gráfico: %s.",
            input$ylms[1], input$ylms[2], 
            ifelse(input$colorBy == "continent", "continente", "país"), 
            paste(input$countries, collapse=", "))
  })
}

# Run the application 
shinyApp(ui = ui, server = server)

15.8 Paso 6: Genera una segunda gráfica

library(shiny)
library(dslabs)
library(magrittr)
library(ggplot2)
library(tidyverse)
library(ggridges)
data(gapminder)

ui <- fluidPage(
  # Application title
  titlePanel("Visualización exploratoria de gapminder"),
  # Sidebar for parameters
  sidebarLayout(
    sidebarPanel(
      ## Código para seleccionar paises
      selectizeInput( 'countries', label = h3("Seleccionar paises"), 
                      choices = levels(gapminder$country), multiple=TRUE),
      sliderInput( 'ylms', label = h3("Años contemplados"), min = 1960, 
                   max = 2020, value = c(1960, 2016) ),
      radioButtons( 'colorBy', label=h3("Colorear por"), 
                    choices = c(pais="country", continente="continent"), 
                    selected = "continent" )
    ),
    mainPanel(
      tabsetPanel(
        tabPanel("Esperanza de vida", 
                 plotOutput("lifeExpPlot"),
                 textOutput("plotLegend"),
                 plotOutput("fertilityPlot"))
      )
    )
  )
)

# Define server logic
server <- function(input, output) {
  output$lifeExpPlot <- renderPlot({
    gapminder %>%
      filter( country %in% input$countries ) %>%
      ggplot( aes( year, life_expectancy, col=get(input$colorBy), group=country )) +
      geom_point( size=0.3 ) +
      geom_line( ) +
      coord_cartesian(xlim=c(input$ylms[1], input$ylms[2])) +
      labs(col=input$colorBy)
  })
  output$plotLegend <- renderText({ 
    sprintf("Datos de esperanza de vida del año %d al año %d. Cada color 
    representa un %s. Los siguientes países estan representados en el gráfico: %s.",
            input$ylms[1], input$ylms[2], 
            ifelse(input$colorBy == "continent", "continente", "país"), 
            paste(input$countries, collapse=", "))
  })
  output$fertilityPlot <- renderPlot({
    gapminder %>%
      filter( country %in% input$countries ) %>%
      ggplot( aes( year, fertility, col=get(input$colorBy), group=country )) +
      geom_point( size=0.3 ) +
      geom_line( ) +
      coord_cartesian(xlim=c(input$ylms[1], input$ylms[2])) +
      labs(col=input$colorBy)
  })
}

# Run the application 
shinyApp(ui = ui, server = server)

15.9 Paso 7: Expresiones reactivas

library(shiny)
library(dslabs)
library(magrittr)
library(ggplot2)
library(tidyverse)
library(ggridges)
data(gapminder)

ui <- fluidPage(
  # Application title
  titlePanel("Visualización exploratoria de gapminder"),
  # Sidebar for parameters
  sidebarLayout(
    sidebarPanel(
      ## Código para seleccionar paises
      selectizeInput( 'countries', label = h3("Seleccionar paises"), 
                      choices = levels(gapminder$country), multiple=TRUE),
      sliderInput( 'ylms', label = h3("Años contemplados"), min = 1960, 
                   max = 2020, value = c(1960, 2016) ),
      radioButtons( 'colorBy', label=h3("Colorear por"), 
                    choices = c(pais="country", continente="continent"), 
                    selected = "continent" )
    ),
    mainPanel(
      tabsetPanel(
        tabPanel("Esperanza de vida", 
                 plotOutput("lifeExpPlot"),
                 textOutput("plotLegend"),
                 plotOutput("fertilityPlot")
        )
      )
    )
  )
)

# Define server logic
server <- function(input, output) {
  gapminderSub <- reactive({
    gapminder %>%
      filter( country %in% input$countries )
  })
  output$lifeExpPlot <- renderPlot({
    gapminderSub() %>%  
      ggplot( aes( year, life_expectancy, col=get(input$colorBy), group=country )) +
      geom_point( size=0.3 ) +
      geom_line( ) +
      coord_cartesian(xlim=c(input$ylms[1], input$ylms[2])) +
      labs(col=input$colorBy)
  })
  output$plotLegend <- renderText({ 
    sprintf("Datos de esperanza de vida del año %d al año %d. Cada color 
    representa un %s. Los siguientes países estan representados en el gráfico: %s.",
            input$ylms[1], input$ylms[2], 
            ifelse(input$colorBy == "continent", "continente", "país"), 
            paste(input$countries, collapse=", "))
  })
  output$fertilityPlot <- renderPlot({
    gapminderSub() %>%
      ggplot( aes( year, fertility, col=get(input$colorBy), group=country )) +
      geom_point( size=0.3 ) +
      geom_line( ) +
      coord_cartesian(xlim=c(input$ylms[1], input$ylms[2])) +
      labs(col=input$colorBy)
  })
}

# Run the application 
shinyApp(ui = ui, server = server)library(shiny)
library(dslabs)
library(magrittr)
library(ggplot2)
library(tidyverse)
library(ggridges)
data(gapminder)

ui <- fluidPage(
  # Application title
  titlePanel("Visualización exploratoria de gapminder"),
  # Sidebar for parameters
  sidebarLayout(
    sidebarPanel(
      ## Código para seleccionar paises
      selectizeInput( 'countries', label = h3("Seleccionar paises"), 
                      choices = levels(gapminder$country), multiple=TRUE),
      sliderInput( 'ylms', label = h3("Años contemplados"), min = 1960, 
                   max = 2020, value = c(1960, 2016) ),
      radioButtons( 'colorBy', label=h3("Colorear por"), 
                    choices = c(pais="country", continente="continent"), 
                    selected = "continent" )
    ),
    mainPanel(
      tabsetPanel(
        tabPanel("Esperanza de vida", 
                 plotOutput("lifeExpPlot"),
                 textOutput("plotLegend"),
                 plotOutput("fertilityPlot")
        )
      )
    )
  )
)

# Define server logic
server <- function(input, output) {
  gapminderSub <- reactive({
    gapminder %>%
      filter( country %in% input$countries )
  })
  output$lifeExpPlot <- renderPlot({
    gapminderSub() %>%  
      ggplot( aes( year, life_expectancy, col=get(input$colorBy), group=country )) +
      geom_point( size=0.3 ) +
      geom_line( ) +
      coord_cartesian(xlim=c(input$ylms[1], input$ylms[2])) +
      labs(col=input$colorBy)
  })
  output$plotLegend <- renderText({ 
    sprintf("Datos de esperanza de vida del año %d al año %d. Cada color 
    representa un %s. Los siguientes países estan representados en el gráfico: %s.",
            input$ylms[1], input$ylms[2], 
            ifelse(input$colorBy == "continent", "continente", "país"), 
            paste(input$countries, collapse=", "))
  })
  output$fertilityPlot <- renderPlot({
    gapminderSub() %>%
      ggplot( aes( year, fertility, col=get(input$colorBy), group=country )) +
      geom_point( size=0.3 ) +
      geom_line( ) +
      coord_cartesian(xlim=c(input$ylms[1], input$ylms[2])) +
      labs(col=input$colorBy)
  })
}

# Run the application 
shinyApp(ui = ui, server = server)

15.10 Paso 8: Agrega una segunda pestaña

library(shiny)
library(dslabs)
library(magrittr)
library(ggplot2)
library(tidyverse)
library(ggridges)
data(gapminder)

ui <- fluidPage(
  # Application title
  titlePanel("Visualización exploratoria de gapminder"),
  # Sidebar for parameters
  sidebarLayout(
    sidebarPanel(
      ## Código para seleccionar paises
      selectizeInput( 'countries', label = h3("Seleccionar paises"), 
                      choices = levels(gapminder$country), multiple=TRUE),
      sliderInput( 'ylms', label = h3("Años contemplados"), min = 1960, 
                   max = 2020, value = c(1960, 2016) ),
      radioButtons( 'colorBy', label=h3("Colorear por"), 
                    choices = c(pais="country", continente="continent"), 
                    selected = "continent" )
    ),
    mainPanel(
      tabsetPanel(
        tabPanel("Esperanza de vida", 
                 plotOutput("lifeExpPlot"),
                 textOutput("plotLegend")),
        tabPanel("Fertilidad", 
                 plotOutput("fertilityPlot"))
      )
    )
  )
)

# Define server logic
server <- function(input, output) {
  gapminderSub <- reactive({
    gapminder %>%
      filter( country %in% input$countries )
  })
  output$lifeExpPlot <- renderPlot({
    gapminderSub() %>%  
      ggplot( aes( year, life_expectancy, col=get(input$colorBy), group=country )) +
      geom_point( size=0.3 ) +
      geom_line( ) +
      coord_cartesian(xlim=c(input$ylms[1], input$ylms[2])) +
      labs(col=input$colorBy)
  })
  output$plotLegend <- renderText({ 
    sprintf("Datos de esperanza de vida del año %d al año %d. Cada color 
    representa un %s. Los siguientes países estan representados en el gráfico: %s.",
            input$ylms[1], input$ylms[2], 
            ifelse(input$colorBy == "continent", "continente", "país"), 
            paste(input$countries, collapse=", "))
  })
  output$fertilityPlot <- renderPlot({
    gapminderSub() %>%
      ggplot( aes( year, fertility, col=get(input$colorBy), group=country )) +
      geom_point( size=0.3 ) +
      geom_line( ) +
      coord_cartesian(xlim=c(input$ylms[1], input$ylms[2])) +
      labs(col=input$colorBy)
  })
}

# Run the application 
shinyApp(ui = ui, server = server)

15.11 Paso 9: Agrega una tercer pestaña

library(shiny)
library(dslabs)
library(magrittr)
library(ggplot2)
library(tidyverse)
library(ggridges)
data(gapminder)

ui <- fluidPage(
  # Application title
  titlePanel("Visualización exploratoria de gapminder"),
  # Sidebar for parameters
  sidebarLayout(
    sidebarPanel(
      ## Código para seleccionar paises
      selectizeInput( 'countries', label = h3("Seleccionar paises"), 
                      choices = levels(gapminder$country), multiple=TRUE),
      sliderInput( 'ylms', label = h3("Años contemplados"), min = 1960, 
                   max = 2020, value = c(1960, 2016) ),
      radioButtons( 'colorBy', label=h3("Colorear por"), 
                    choices = c(pais="country", continente="continent"), 
                    selected = "continent" )
    ),
    mainPanel(
      tabsetPanel(
        tabPanel("Esperanza de vida", 
                 plotOutput("lifeExpPlot"),
                 textOutput("plotLegend")),
        tabPanel("Fertilidad", 
                 plotOutput("fertilityPlot")),
        tabPanel("Riqueza sobre tiempo", 
                 plotOutput("ridgesPlot"))
      )
    )
  )
)

# Define server logic
server <- function(input, output) {
  gapminderSub <- reactive({
    gapminder %>%
      filter( country %in% input$countries )
  })
  output$lifeExpPlot <- renderPlot({
    gapminderSub() %>%  
      ggplot( aes( year, life_expectancy, col=get(input$colorBy), group=country )) +
      geom_point( size=0.3 ) +
      geom_line( ) +
      coord_cartesian(xlim=c(input$ylms[1], input$ylms[2])) +
      labs(col=input$colorBy)
  })
  output$plotLegend <- renderText({ 
    sprintf("Datos de esperanza de vida del año %d al año %d. Cada color 
    representa un %s. Los siguientes países estan representados en el gráfico: %s.",
            input$ylms[1], input$ylms[2], 
            ifelse(input$colorBy == "continent", "continente", "país"), 
            paste(input$countries, collapse=", "))
  })
  output$fertilityPlot <- renderPlot({
    gapminderSub() %>%
      ggplot( aes( year, fertility, col=get(input$colorBy), group=country )) +
      geom_point( size=0.3 ) +
      geom_line( ) +
      coord_cartesian(xlim=c(input$ylms[1], input$ylms[2])) +
      labs(col=input$colorBy)
  })
  output$ridgesPlot <- renderPlot({
    keep_regions <- gapminderSub() %>%
      pull( region ) %>%
      as.character %>%
      unique
    gapminder %>%
      mutate( dollars_per_day=gdp/population/365 ) %>%
      filter( year %in% seq(1960, 2010, 10), 
              !is.na(dollars_per_day), 
              region %in% keep_regions ) %>%
      filter( between(year, input$ylms[1], input$ylms[2]) ) %>%
      ggplot( aes( dollars_per_day, factor(year) ) ) +
      scale_x_continuous(trans = "log2")  +
      geom_density_ridges(jittered_points = TRUE) +
      facet_grid( ~region, scales="free")
  })
}

# Run the application 
shinyApp(ui = ui, server = server)

15.12 Paso 10: Corrigiendo el error cuando no hay datos

library(shiny)
library(dslabs)
library(magrittr)
library(ggplot2)
library(tidyverse)
library(ggridges)
data(gapminder)

ui <- fluidPage(
  # Application title
  titlePanel("Visualización exploratoria de gapminder"),
  # Sidebar for parameters
  sidebarLayout(
    sidebarPanel(
      ## Código para seleccionar paises
      selectizeInput( 'countries', label = h3("Seleccionar paises"), 
                      choices = levels(gapminder$country), multiple=TRUE),
      sliderInput( 'ylms', label = h3("Años contemplados"), min = 1960, 
                   max = 2020, value = c(1960, 2016) ),
      radioButtons( 'colorBy', label=h3("Colorear por"), 
                    choices = c(pais="country", continente="continent"), 
                    selected = "continent" )
    ),
    mainPanel(
      tabsetPanel(
        tabPanel("Esperanza de vida", 
                 plotOutput("lifeExpPlot"),
                 textOutput("plotLegend")),
        tabPanel("Fertilidad", 
                 plotOutput("fertilityPlot")),
        tabPanel("Riqueza sobre tiempo", 
                 plotOutput("ridgesPlot"))
      )
    )
  )
)

# Define server logic
server <- function(input, output) {
  gapminderSub <- reactive({
    gapminder %>%
      filter( country %in% input$countries )
  })
  output$lifeExpPlot <- renderPlot({
    gapminderSub() %>%  
      ggplot( aes( year, life_expectancy, col=get(input$colorBy), group=country )) +
      geom_point( size=0.3 ) +
      geom_line( ) +
      coord_cartesian(xlim=c(input$ylms[1], input$ylms[2])) +
      labs(col=input$colorBy)
  })
  output$plotLegend <- renderText({ 
    sprintf("Datos de esperanza de vida del año %d al año %d. Cada color 
    representa un %s. Los siguientes países estan representados en el gráfico: %s.",
            input$ylms[1], input$ylms[2], 
            ifelse(input$colorBy == "continent", "continente", "país"), 
            paste(input$countries, collapse=", "))
  })
  output$fertilityPlot <- renderPlot({
    gapminderSub() %>%
      ggplot( aes( year, fertility, col=get(input$colorBy), group=country )) +
      geom_point( size=0.3 ) +
      geom_line( ) +
      coord_cartesian(xlim=c(input$ylms[1], input$ylms[2])) +
      labs(col=input$colorBy)
  })
  output$ridgesPlot <- renderPlot({
    keep_regions <- gapminderSub() %>%
      pull( region ) %>%
      as.character %>%
      unique
    req( length(keep_regions) > 0 )
    gapminder %>%
      mutate( dollars_per_day=gdp/population/365 ) %>%
      filter( year %in% seq(1960, 2010, 10), 
              !is.na(dollars_per_day), 
              region %in% keep_regions ) %>%
      filter( between(year, input$ylms[1], input$ylms[2]) ) %>%
      ggplot( aes( dollars_per_day, factor(year) ) ) +
      scale_x_continuous(trans = "log2")  +
      geom_density_ridges(jittered_points = TRUE) +
      facet_grid( ~region, scales="free")
  })
}

# Run the application 
shinyApp(ui = ui, server = server)

15.13 Paso 11: Agregando opciones para un panel en específico (checkbox)

library(shiny)
library(dslabs)
library(magrittr)
library(ggplot2)
library(tidyverse)
library(ggridges)
data(gapminder)

ui <- fluidPage(
  # Application title
  titlePanel("Visualización exploratoria de gapminder"),
  # Sidebar for parameters
  sidebarLayout(
    sidebarPanel(
      ## Código para seleccionar paises
      selectizeInput( 'countries', label = h3("Seleccionar paises"), 
                      choices = levels(gapminder$country), multiple=TRUE),
      sliderInput( 'ylms', label = h3("Años contemplados"), min = 1960, 
                   max = 2020, value = c(1960, 2016) ),
      radioButtons( 'colorBy', label=h3("Colorear por"), 
                    choices = c(pais="country", continente="continent"), 
                    selected = "continent" )
    ),
    mainPanel(
      tabsetPanel(
        tabPanel("Esperanza de vida", 
                 plotOutput("lifeExpPlot"),
                 textOutput("plotLegend")),
        tabPanel("Fertilidad", 
                 plotOutput("fertilityPlot")),
        tabPanel("Riqueza sobre tiempo", 
                 checkboxInput("indObs", 
                               "Observaciones individuales", value = TRUE),
                 plotOutput("ridgesPlot"))
      )
    )
  )
)

# Define server logic
server <- function(input, output) {
  gapminderSub <- reactive({
    gapminder %>%
      filter( country %in% input$countries )
  })
  output$lifeExpPlot <- renderPlot({
    gapminderSub() %>%  
      ggplot( aes( year, life_expectancy, col=get(input$colorBy), group=country )) +
      geom_point( size=0.3 ) +
      geom_line( ) +
      coord_cartesian(xlim=c(input$ylms[1], input$ylms[2])) +
      labs(col=input$colorBy)
  })
  output$plotLegend <- renderText({ 
    sprintf("Datos de esperanza de vida del año %d al año %d. Cada color 
    representa un %s. Los siguientes países estan representados en el gráfico: %s.",
            input$ylms[1], input$ylms[2], 
            ifelse(input$colorBy == "continent", "continente", "país"), 
            paste(input$countries, collapse=", "))
  })
  output$fertilityPlot <- renderPlot({
    gapminderSub() %>%
      ggplot( aes( year, fertility, col=get(input$colorBy), group=country )) +
      geom_point( size=0.3 ) +
      geom_line( ) +
      coord_cartesian(xlim=c(input$ylms[1], input$ylms[2])) +
      labs(col=input$colorBy)
  })
  output$ridgesPlot <- renderPlot({
    keep_regions <- gapminderSub() %>%
      pull( region ) %>%
      as.character %>%
      unique
    req( length(keep_regions) > 0 )
    gapminder %>%
      mutate( dollars_per_day=gdp/population/365 ) %>%
      filter( year %in% seq(1960, 2010, 10), 
              !is.na(dollars_per_day), 
              region %in% keep_regions ) %>%
      filter( between(year, input$ylms[1], input$ylms[2]) ) %>%
      ggplot( aes( dollars_per_day, factor(year) ) ) +
      scale_x_continuous(trans = "log2")  +
      geom_density_ridges(jittered_points = input$indObs) +
      facet_grid( ~region, scales="free")
  })
}

# Run the application 
shinyApp(ui = ui, server = server)

15.14 Paso 12: Operaciones que esperan una orden para ser ejecutadas

library(shiny)
library(dslabs)
library(magrittr)
library(ggplot2)
library(tidyverse)
library(ggridges)
data(gapminder)

ui <- fluidPage(
  # Application title
  titlePanel("Visualización exploratoria de gapminder"),
  # Sidebar for parameters
  sidebarLayout(
    sidebarPanel(
      ## Código para seleccionar paises
      selectizeInput( 'countries', label = h3("Seleccionar paises"), 
                      choices = levels(gapminder$country), multiple=TRUE),
      sliderInput( 'ylms', label = h3("Años contemplados"), min = 1960, 
                   max = 2020, value = c(1960, 2016) ),
      radioButtons( 'colorBy', label=h3("Colorear por"), 
                    choices = c(pais="country", continente="continent"), 
                    selected = "continent" )
    ),
    mainPanel(
      tabsetPanel(
        tabPanel("Esperanza de vida", 
                 plotOutput("lifeExpPlot"),
                 textOutput("plotLegend")),
        tabPanel("Fertilidad", 
                 plotOutput("fertilityPlot")),
        tabPanel("Riqueza sobre tiempo", 
                 checkboxInput("indObs", 
                               "Observaciones individuales", value = TRUE),
                 actionButton("ridgesAction", "Actualizar paises"),
                 plotOutput("ridgesPlot"))
      )
    )
  )
)

# Define server logic
server <- function(input, output) {
  gapminderSub <- reactive({
    gapminder %>%
      filter( country %in% input$countries )
  })
  output$lifeExpPlot <- renderPlot({
    gapminderSub() %>%  
      ggplot( aes( year, life_expectancy, col=get(input$colorBy), group=country )) +
      geom_point( size=0.3 ) +
      geom_line( ) +
      coord_cartesian(xlim=c(input$ylms[1], input$ylms[2])) +
      labs(col=input$colorBy)
  })
  output$plotLegend <- renderText({ 
    sprintf("Datos de esperanza de vida del año %d al año %d. Cada color 
    representa un %s. Los siguientes países estan representados en el gráfico: %s.",
            input$ylms[1], input$ylms[2], 
            ifelse(input$colorBy == "continent", "continente", "país"), 
            paste(input$countries, collapse=", "))
  })
  output$fertilityPlot <- renderPlot({
    gapminderSub() %>%
      ggplot( aes( year, fertility, col=get(input$colorBy), group=country )) +
      geom_point( size=0.3 ) +
      geom_line( ) +
      coord_cartesian(xlim=c(input$ylms[1], input$ylms[2])) +
      labs(col=input$colorBy)
  })
  keep_regions <- eventReactive( input$ridgesAction, {
    gapminderSub() %>%
      pull( region ) %>%
      as.character %>%
      unique
  })
  output$ridgesPlot <- renderPlot({
    req( length(keep_regions()) > 0 )
    gapminder %>%
      mutate( dollars_per_day=gdp/population/365 ) %>%
      filter( year %in% seq(1960, 2010, 10), 
              !is.na(dollars_per_day), 
              region %in% keep_regions() ) %>%
      filter( between(year, input$ylms[1], input$ylms[2]) ) %>%
      ggplot( aes( dollars_per_day, factor(year) ) ) +
      scale_x_continuous(trans = "log2")  +
      geom_density_ridges(jittered_points = input$indObs) +
      facet_grid( ~region, scales="free")
  })
}

# Run the application 
shinyApp(ui = ui, server = server)