始める無料で始める

はじめての shinyApp

入力と出力をどのように組み合わせて shinyApp にできるかを見てきました。また、睡眠に関する研究結果を伝える shinyApp の構成方法も学びました。

ここでは次の2つの主要な結果をレポートする shinyApp を作成します。

  1. 睡眠時間の分布
  2. 年齢層ごとの睡眠時間の中央値

この演習では、データは sleep という dplyr のデータフレームに保存されており、shinytidyverse ライブラリはすでに読み込まれています。

それでは、あなた自身の shinyApp を作成してみましょう!

この演習はコースの一部です

shinydashboard で作るダッシュボード

コースを見る

演習の手順

  • mainPanel に「histogram」と「barchart」という2つのプロット出力を追加してください。
  • checkboxGroupInput()choiceNames 引数の中身を、"calendar"、"briefcase"、"gift" という名前のアイコンに置き換えてください。
  • 2つの出力を定義します。1つは histogram、もう1つは barchart です。
  • shinyApp() 関数を使って shiny アプリをレンダーしてください。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

ui <- fluidPage(
  titlePanel("Sleeping habits in America"), 
  fluidRow(
  # Place two plots here, called "histogram" and "barchart"
  mainPanel(___("histogram"), ___("barchart")), 
  inputPanel(sliderInput("binwidth", 
                         label = "Bin width", 
                         min = 0.1, max = 2, 
                         step = 0.01, value=0.25),
             checkboxGroupInput("days", "Choose types of days:",
                                # Replace the list elements with icons called "calendar", "briefcase" and "gift"
                                choiceNames = list("All days", 
                                                   "Non-holiday weekdays", 
                                                   "Weekend days/holidays"), 
                                choiceValues = list("All days", 
                                                    "Nonholiday weekdays", 
                                                    "Weekend days and holidays"))), 
  "In general, across the different age groups, Americans seem to get adequate daily rest." ))

server <- function(input, output, session) {
  # Define the histogram and barchart
  output$histogram <- ___({
    ggplot(sleep, aes(x=`Avg hrs per day sleeping`)) + 
    geom_histogram(binwidth = input$binwidth, col='white') + 
    theme_classic()
  })
  ___ <- ___({
    filter(sleep, `Type of Days` %in% input$days) %>%
      group_by(`Type of Days`, `Age Group`) %>%
      summarize(`Median hours` = median(`Avg hrs per day sleeping`)) %>%
      ggplot(aes(x = `Median hours`, y = `Age Group`, fill = `Type of Days`)) +
      geom_col(position = 'dodge') + theme_classic()
  })
}

# Use shinyApp() to render the shinyApp
___
コードを編集して実行