iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 20
2
Data Technology

你都在公司都在幹啥R? R語言資料分析經驗分享系列 第 20

【20】當老闆嘟著嘴問:前面幾天你展示了很多資料分析手法,但是公司很多人不會寫程試,你有辦法嗎?

我自己是工程師,所以當公司有不同需求時,大部分的時候我都能靠程式實作去完成任務,但是有些時候資料更新是連續的,每次業務或行銷團隊有需要時,如果每次都找你幫忙解析資料,那還真是一件麻煩的事情,所以這幾天的介紹中,我會講講shiny ,這套將資料變成網頁的一個工具。

首先是安裝並使用

install.packages("shiny")
library(shiny)

第一次使用當然就先用官方樣板來開局。

runExample("01_hello")

這時候會跳出一個新的視窗。

https://ithelp.ithome.com.tw/upload/images/20180106/20107299IH403aElmI.png

很特別的是shiny 所產生的頁面是可以互動的,左上方的Number of bins 是可以拉動的,而下方附上的是sample 的程式碼,底下讓我們來討論shiny 的架構。

Shiny主要由兩部分的程式碼組成,一個是ui ,顧名思義就是掌管畫面的配置,像是標題用titlePanel,sidebarLayout 就是側邊欄區塊,在這區塊放置用來滑動的sliderInput,mainPanel 則是負責圖表的顯示,我們在裡面畫出output 。

# Define UI for app that draws a histogram ----
ui <- fluidPage(

  # App title ----
  titlePanel("Hello Shiny!"),

  # Sidebar layout with input and output definitions ----
  sidebarLayout(

    # Sidebar panel for inputs ----
    sidebarPanel(

      # Input: Slider for the number of bins ----
      sliderInput(inputId = "bins",
                  label = "Number of bins:",
                  min = 1,
                  max = 50,
                  value = 30)

    ),

    # Main panel for displaying outputs ----
    mainPanel(

      # Output: Histogram ----
      plotOutput(outputId = "distPlot")

    )
  )
)

另一段server 區塊則是偏重邏輯的處理,在這邊可以看到distPlot 這個結果中有x, bins 兩個變數,x的資料來自faithful(這是R 的內建資料集,詳見),bins 則是一段數列,最後我們將以上結果化成長條圖hist。

# Define server logic required to draw a histogram ----
server <- function(input, output) {

  # Histogram of the Old Faithful Geyser Data ----
  # with requested number of bins
  # This expression that generates a histogram is wrapped in a call
  # to renderPlot to indicate that:
  #
  # 1. It is "reactive" and therefore should be automatically
  #    re-executed when inputs (input$bins) change
  # 2. Its output type is a plot
  output$distPlot <- renderPlot({

    x    <- faithful$waiting
    bins <- seq(min(x), max(x), length.out = input$bins + 1)

    hist(x, breaks = bins, col = "#75AADB", border = "white",
         xlab = "Waiting time to next eruption (in mins)",
         main = "Histogram of waiting times")

    })

}

我們可以發現我們在server 裡將相關結果存到output$distPlot,在看到ui 區塊,將distPlot 畫出。最後執行shinyApp就可以得到我們的結果囉!

shinyApp(ui = ui, server = server)

以上就是shiny系列的第一篇文章!

Ref:
今天沒有程式碼


上一篇
【19】當老闆突然(再)^4問:用了多次k-means 後真的有比較好嗎?說說看啊!
下一篇
【21】當老闆眼睛blink blink地問:哦?這看起來很方便,那我們公司的資料怎麼在shiny 上呈現?
系列文
你都在公司都在幹啥R? R語言資料分析經驗分享30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言