マックブックな日々(Macbook Geek)

Retina Macbook Proで行った設定、アプリのインストール、トラブル対策等の覚書

Shinyを使ってみる

参考:Tutorial: Building 'Shiny' Applications with R
Shinyのアプリは
アプリ名を表すフォルダの下に、

  • ユーザインタフェースを定義する、ui.R
  • サーバーサイドの処理を定義する、server.R

の2つのファイルが存在しなければならない。
これら以外のスクリプトやデータがあってもよい。

例えば、"ex01"と言うフォルダを作り、その下に次の2つのRファイルをを作る。

ui.R

library(shiny)

# Define UI for application that plots random distributions 
shinyUI(pageWithSidebar(

  # Application title
  headerPanel("Hello Shiny!"),

  # Sidebar with a slider input for number of observations
  sidebarPanel(
    sliderInput("obs", 
                "Number of observations:", 
                min = 0, 
                max = 1000, 
                value = 500)
  ),

  # Show a plot of the generated distribution
  mainPanel(
    plotOutput("distPlot")
  )
))

server.R

library(shiny)

# Define server logic required to generate and plot a random distribution
shinyServer(function(input, output) {

  # Function that generates a plot of the distribution. The function
  # is wrapped in a call to reactivePlot to indicate that:
  #
  #  1) It is "reactive" and therefore should be automatically 
  #     re-executed when inputs change
  #  2) Its output type is a plot 
  #
  output$distPlot <- reactivePlot(function() {

    # generate an rnorm distribution and plot it
    dist <- rnorm(input$obs)
    hist(dist)
  })
})

実行は、

> runApp("アプリ名(フォルダ名)")

とする。
上の例の場合、アプリフォルダを含むフォルダに作業ディレクトリを変更し(トップメニューの「その他」-「作業ディレクトリの変更...」)、コンソールに次を入力する。

> runApp("ex01")