ふんわり R-tips

ぜんぜんわからない、俺たちは雰囲気でRをやっている

Shinyサンプルアプリケーション「05_sliders」の説明

05_slidersは、5つのスライダーと、その値をテキスト表示する例です。

「05_sliders」の実行

library(shiny)
runExample("05_sliders")

f:id:phmpk:20161230154703p:plain

server.R

library(shiny)

# サーバー側のスライダーの動作を定義
function(input, output) {
  
  # すべての変数に対応するreactiveな動作を定義
  sliderValues <- reactive({
    
    # データフレームの構成
    data.frame(
      Name = c("Integer", 
               "Decimal",
               "Range",
               "Custom Format",
               "Animation"),
      Value = as.character(c(input$integer, 
                             input$decimal,
                             paste(input$range, collapse=' '),
                             input$format,
                             input$animation)), 
      stringsAsFactors=FALSE)
  }) 
  
  # HTMLの表を出力
  output$values <- renderTable({
    sliderValues()
  })
}

Code license:MIT

  • スライドバーからの入力を、as.character()で文字列としてデータフレームを構成して、reactiveにsliderValuesに代入

  • sliderValues()をoutput$valuesとしてHTMLの表を出力

ui.R

library(shiny)

# スライダーデモのUIを定義
fluidPage(

  # タイトル
  titlePanel("Sliders"),

  # サイドバーに多様なオプションを付けたスライドバーを配置
  sidebarLayout(
    sidebarPanel(
      # シンプルな整数
      sliderInput("integer", "Integer:",
                  min=0, max=1000, value=500),

      # 指定したステップ刻みの10進数
      sliderInput("decimal", "Decimal:",
                  min = 0, max = 1, value = 0.5, step= 0.1),

      # 幅を指定
      sliderInput("range", "Range:",
                  min = 1, max = 1000, value = c(200,500)),

          # アニメーション付きのカスタムフォーマットを指定
      sliderInput("format", "Custom Format:",
                  min = 0, max = 10000, value = 0, step = 2500,
                  pre = "$", sep = ",", animate=TRUE),

          # ループありのアニメーション付きのカスタムフォーマットを指定
      sliderInput("animation", "Looping Animation:", 1, 2000, 1,
                        step = 10, animate=
                            animationOptions(interval=300, loop=TRUE))
    ),

    # 変数のsummaryを表示する表を出力
    mainPanel(
      tableOutput("values")
    )
  )
)

Code license:MIT