2013年10月16日水曜日

Rによる統計解析Webサービスの作成(2) サンプルの作成

まずはRのコンソールからShinyをインストール

options(repos=c(RStudio='http://rstudio.org/_packages', getOption('repos')))
install.packages('shiny') 
 









ui.Rで表示部分を実装
今回はhtmlで記述

index.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>TEST</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> 
 
続いて、server.Rを実装
library(shiny)

# Define server logic for random distribution application
shinyServer(function(input, output) {

  # Reactive expression to generate the requested distribution. This is 
  # called whenever the inputs change. The output renderers defined 
  # below then all used the value computed from this expression
  data <- reactive({  
    dist <- switch(input$dist,
                   norm = rnorm,
                   unif = runif,
                   lnorm = rlnorm,
                   exp = rexp,
                   rnorm)

    dist(input$n)
  })

  # Generate a plot of the data. Also uses the inputs to build the 
  # plot label. Note that the dependencies on both the inputs and
  # the data reactive expression are both tracked, and all expressions 
  # are called in the sequence implied by the dependency graph
  output$plot <- renderPlot({
    dist <- input$dist
    n <- input$n

    hist(data(), 
         main=paste('r', dist, '(', n, ')', sep=''))
  })

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

  # Generate an HTML table view of the data
  output$table <- renderTable({
    data.frame(x=data())
  })
}) 
 
Rのコンソールから実行 
runApp("dir") 


 
 
 
 
 
 
 
 
 
 
 
 
 
ブラウザ上で表示することができた。
次回は試しに回帰分析が出来るものを作ってみる。 

0 件のコメント:

コメントを投稿