Shiny

Структура програми shiny завжди однакова

library(shiny)

ui <- fluidPage()
server <- function(input, output) {}
shinyApp(ui = ui, server = server)
Shiny applications not supported in static R Markdown documents

Для створення програми потрібно створити новий файл app.R

Основна фішка shiny - інтерактивний інтерфейс і інтеграція з R.

library(shiny)

ui <- fluidPage(
  titlePanel("Наша програма"),
  h1("Заголовок"),
  "Тут",
  "можна щось писати",
  br(),
  "Наприклад",
  strong("жирним шрифтом")
)

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

shinyApp(ui, server)
Shiny applications not supported in static R Markdown documents

Спробуємо вивести якісь дані

library(shiny)
library(ggplot2)
ui <- fluidPage(
  titlePanel("Машинки"),
  mainPanel(
    plotOutput("coolplot"),
      tableOutput("results"))
)

server <- function(input, output) {
  
   output$results <- renderTable({
    head(mtcars)})
   
  output$coolplot <-  renderPlot({ggplot(mtcars, aes(x=wt, y=mpg, colour=factor(cyl))) + geom_point()})
  
 
 
}

shinyApp(ui, server)
Shiny applications not supported in static R Markdown documents

Тепер додамо реактивність - тобто дії користувача.

library(shiny)

ui <- pageWithSidebar(
  
  headerPanel("Hello Shiny!"),
  
  sidebarPanel(
    sliderInput("obs", 
                "Number of observations:", 
                min = 1,
                max = 1000, 
                value = 500)
  ),
  
  mainPanel(
    plotOutput("distPlot")
  )
)

server <- function(input, output) {
  
 
  output$distPlot <- renderPlot({
    
    dist <- rnorm(input$obs)
    hist(dist)
    
  })
}

shinyApp(ui = ui, server = server)
Shiny applications not supported in static R Markdown documents

Наступний приклад

library(shiny)

# Define UI for dataset viewer application
ui <- pageWithSidebar(

  # Application title
  headerPanel("Shiny Text"),

  # Sidebar with controls to select a dataset and specify the number
  # of observations to view
  sidebarPanel(
    selectInput("dataset", "Choose a dataset:", 
                choices = c("mtcars", "pressure", "cars")),

    numericInput("obs", "Number of observations to view:", 10)
  ),

  # Show a summary of the dataset and an HTML table with the requested
  # number of observations
  mainPanel(
    verbatimTextOutput("summary"),

    tableOutput("view")
  )
)

# Define server logic required to summarize and view the selected dataset
server <- function(input, output) {

  # Return the requested dataset
  datasetInput <- reactive({
    switch(input$dataset,
           "mtcars" = mtcars,
           "pressure" = pressure,
           "cars" = cars)
  })

  # Generate a summary of the dataset
  output$summary <- renderPrint({
    dataset <- datasetInput()
    summary(dataset)
  })

  # Show the first "n" observations
  output$view <- renderTable({
    head(datasetInput(), n = input$obs)
  })
}

shinyApp(ui = ui, server = server)
Shiny applications not supported in static R Markdown documents

Давайте напишем декілька програм.

Країни - опис і карта

library(maps)
library(shiny)
library(ggplot2)

world_map <- map_data("world2")
countries <- unique(world_map$region)
ui <- pageWithSidebar(

  # Application title
  headerPanel("Країни світу"),

  # Sidebar with controls to select a dataset and specify the number
  # of observations to view
  sidebarPanel(
    selectInput("country", "Виберіть країну:", 
                choices = countries)),

  # Show a summary of the dataset and an HTML table with the requested
  # number of observations
  mainPanel(
    plotOutput("country_map")
  )
)

# Define server logic required to summarize and view the selected dataset
server <- function(input, output) {

  # Return the requested dataset
# datasetInput <- reactive({
 #   switch(input$country,
  #         subset(world_map,world_map$region == country))
#  })

  # Generate a summary of the dataset
  output$country_map <- renderPlot({
    my_country <- subset(world_map,world_map$region == input$country)
    ggplot(my_country, aes(x=long, y=lat, group=group, fill=region)) +
geom_polygon(colour="black") +
scale_fill_brewer(palette="Set2")
  })

}

shinyApp(ui = ui, server = server)
Shiny applications not supported in static R Markdown documents

Приклади на яких можна вчитись:

https://shiny.rstudio.com/

Завдання: Вибір різних графіків для машинок

Вибір вимірів і виведення їх значень

Побудова графіку для вибраного виміру

Побудова графіку для пари вимірів