ふんわり R-tips

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

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

08_htmlは、ui.Rなしで、server.Rで計算した値をHTMLファイルで表示する例です。server.Rは06_tabsetsと全く同じです。

「08_html」の実行

library(shiny)
runExample("08_html")

f:id:phmpk:20161230160208p:plain

server.R

library(shiny)

# ランダムな分布を表示するサーバー側を定義
function(input, output) {
  
  # 分布を生成する
  # 入力が変化したときにreactiveに呼ばれる
  # 下部の出力関数は、ここで生成したreactiveな分布を使用する
  data <- reactive({
    dist <- switch(input$dist,
                   norm = rnorm,
                   unif = runif,
                   lnorm = rlnorm,
                   exp = rexp,
                   rnorm)
    
    dist(input$n)
  })
  
  # dataのプロットとラベルを生成
  # 入力は両方と依存関係があり、どちらかが変化したときはそれに追随して変化する
  output$plot <- renderPlot({
    dist <- input$dist
    n <- input$n
    
    hist(data(), 
         main=paste('r', dist, '(', n, ')', sep=''))
  })
  
  # データのsummaryを生成
  output$summary <- renderPrint({
    summary(data())
  })
  
  # HTMLで表記したデータの表を生成
  output$table <- renderTable({
    data.frame(x=data())
  })
  
}

Code license:MIT

HTML

<html>

<head>
  <script src="shared/jquery.js" type="text/javascript"></script>
  <script src="shared/shiny.js" type="text/javascript"></script>
  <link rel="stylesheet" type="text/css" href="shared/shiny.css"/> 
</head>
 
<body>

  <h1>HTML UI</h1>
 
  <p>
    <label>Distribution type:</label><br />
    <select name="dist">
      <option value="norm">Normal</option>
      <option value="unif">Uniform</option>
      <option value="lnorm">Log-normal</option>
      <option value="exp">Exponential</option>
    </select> 
  </p>
 
  <p>
 
    <label>Number of observations:</label><br /> 
    <input type="number" name="n" value="500" min="1" max="1000" />

  </p>
 
  <pre id="summary" class="shiny-text-output"></pre> 
  
  <div id="plot" class="shiny-plot-output" 
       style="width: 100%; height: 400px"></div> 
  
  <div id="table" class="shiny-html-output"></div>
 
</body>
</html>

Code license:MIT

  • <head></head>でshiny.jsとshiny.css使用を宣言

  • 入力用コントロール<select></select>, <input />で指定したname属性が、server.Rでreactiveな入力input$name, input$nとなる

  • 出力はidとclassを指定して、HTML上に配置する。テキストはshiny-text-ouput、プロットはshiny-plot-output、HTMLの表はshiny-html-outputをclassに指定する