R shiny教程-1:一個 Shiny app的基本組成部分

R shiny

Shiny 是RStudio公司開發(fā)的R包居砖,利用Shiny 可以輕松構(gòu)建交互式Web應(yīng)用程序(App)沿猜。

#安裝Shiny

> install.packages("shiny")

Shiny包中內(nèi)置了11個例子來展示Shiny的使用澳厢。

#Example 1: Hello Shiny

Hello Shiny Screenshot

Hello Shiny 使用faithful數(shù)據(jù)畫了一個直方圖夯到,這個直方圖可以調(diào)節(jié)bin的個數(shù)房铭。

Hello Shiny運行

> library(shiny)
> runExample("01_hello")

Shiny App的架構(gòu)
Shiny App 本質(zhì)上基于一個R腳本(app.R).

app.R 有三個組成成分:

  • 一個用戶界面
  • 一個服務(wù)器功能
  • 調(diào)用shinyApp函數(shù)

用戶界面(ui)包含了App的的布局和外觀掺出。
服務(wù)器功能(server)包含了電腦構(gòu)建app需要的指令。
shinyApp 函數(shù)根據(jù)UI/server創(chuàng)建Shiny app惭等。

注:版本0.10.2以前珍手,Shiny 不支持一個文件構(gòu)建App,uiserver各自需要一個單獨的文件:i.R and server.R辞做。

#Hello Shiny

##用戶界面:ui

library(shiny)

# 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")

    )
  )
)

##服務(wù)器功能:server

# 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")

    })

}

##shiny App 運行

shinyApp函數(shù)根據(jù)上面構(gòu)建的UI/server創(chuàng)建Shiny app

shinyApp(ui, server)

#Example 2: Shiny Text

Tabsets Screenshot
library(shiny)
runExample("02_text")

##ui

# Define UI for dataset viewer app ----
ui <- fluidPage(

  # App title ----
  titlePanel("Shiny Text"),

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

    # Sidebar panel for inputs ----
    sidebarPanel(

      # Input: Selector for choosing dataset ----
      selectInput(inputId = "dataset",
                  label = "Choose a dataset:",
                  choices = c("rock", "pressure", "cars")),

      # Input: Numeric entry for number of obs to view ----
      numericInput(inputId = "obs",
                   label = "Number of observations to view:",
                   value = 10)
    ),

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

      # Output: Verbatim text for data summary ----
      verbatimTextOutput("summary"),

      # Output: HTML table with requested number of observations ----
      tableOutput("view")

    )
  )
)

##server

# Define server logic to summarize and view selected dataset ----
server <- function(input, output) {

  # Return the requested dataset ----
  datasetInput <- reactive({
    switch(input$dataset,
           "rock" = rock,
           "pressure" = pressure,
           "cars" = cars)
  })

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

  # Show the first "n" observations ----
  output$view <- renderTable({
    head(datasetInput(), n = input$obs)
  })

}

#Example 3: Reactivity

[站外圖片上傳中...(image-930865-1560176024515)]

library(shiny)
runExample("03_reactivity")
  • 響應(yīng)式編程

響應(yīng)式編程是一種面向數(shù)據(jù)流和變化傳播的編程范式琳要。

input values => R code => output values

input values變化時,R code會自動執(zhí)行秤茅,同時更新結(jié)果

使用reactive()可以創(chuàng)建響應(yīng)式表達式

datasetInput <- reactive({
   switch(input$dataset,
          "rock" = rock,
          "pressure" = pressure,
          "cars" = cars)
})

改變input或者input$obs, 下面的表達式都會重新運行稚补。

output$view <- renderTable({
   head(datasetInput(), n = input$obs)
})

##ui

# Define UI for dataset viewer app ----
ui <- fluidPage(

  # App title ----
  titlePanel("Reactivity"),

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

    # Sidebar panel for inputs ----
    sidebarPanel(

      # Input: Text for providing a caption ----
      # Note: Changes made to the caption in the textInput control
      # are updated in the output area immediately as you type
      textInput(inputId = "caption",
                label = "Caption:",
                value = "Data Summary"),

      # Input: Selector for choosing dataset ----
      selectInput(inputId = "dataset",
                  label = "Choose a dataset:",
                  choices = c("rock", "pressure", "cars")),

      # Input: Numeric entry for number of obs to view ----
      numericInput(inputId = "obs",
                   label = "Number of observations to view:",
                   value = 10)

    ),

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

      # Output: Formatted text for caption ----
      h3(textOutput("caption", container = span)),

      # Output: Verbatim text for data summary ----
      verbatimTextOutput("summary"),

      # Output: HTML table with requested number of observations ----
      tableOutput("view")

    )
  )
)

##server

# Define server logic to summarize and view selected dataset ----
server <- function(input, output) {

  # Return the requested dataset ----
  # By declaring datasetInput as a reactive expression we ensure
  # that:
  #
  # 1. It is only called when the inputs it depends on changes
  # 2. The computation and result are shared by all the callers,
  #    i.e. it only executes a single time
  datasetInput <- reactive({
    switch(input$dataset,
           "rock" = rock,
           "pressure" = pressure,
           "cars" = cars)
  })

  # Create caption ----
  # The output$caption is computed based on a reactive expression
  # that returns input$caption. When the user changes the
  # "caption" field:
  #
  # 1. This function is automatically called to recompute the output
  # 2. New caption is pushed back to the browser for re-display
  #
  # Note that because the data-oriented reactive expressions
  # below don't depend on input$caption, those expressions are
  # NOT called when input$caption changes
  output$caption <- renderText({
    input$caption
  })

  # Generate a summary of the dataset ----
  # The output$summary depends on the datasetInput reactive
  # expression, so will be re-executed whenever datasetInput is
  # invalidated, i.e. whenever the input$dataset changes
  output$summary <- renderPrint({
    dataset <- datasetInput()
    summary(dataset)
  })

  # Show the first "n" observations ----
  # The output$view depends on both the databaseInput reactive
  # expression and input$obs, so it will be re-executed whenever
  # input$dataset or input$obs is changed
  output$view <- renderTable({
    head(datasetInput(), n = input$obs)
  })

}

#原文:

The basic parts of a Shiny app

系列文章
R shiny教程-1:一個 Shiny app的基本組成部分
R shiny教程-2:布局用戶界面
Shiny Server安裝

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市框喳,隨后出現(xiàn)的幾起案子课幕,更是在濱河造成了極大的恐慌厦坛,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,013評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件乍惊,死亡現(xiàn)場離奇詭異杜秸,居然都是意外死亡,警方通過查閱死者的電腦和手機润绎,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,205評論 2 382
  • 文/潘曉璐 我一進店門撬碟,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人凡橱,你說我怎么就攤上這事小作。” “怎么了稼钩?”我有些...
    開封第一講書人閱讀 152,370評論 0 342
  • 文/不壞的土叔 我叫張陵顾稀,是天一觀的道長。 經(jīng)常有香客問我坝撑,道長静秆,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,168評論 1 278
  • 正文 為了忘掉前任巡李,我火速辦了婚禮抚笔,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘侨拦。我一直安慰自己殊橙,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 64,153評論 5 371
  • 文/花漫 我一把揭開白布狱从。 她就那樣靜靜地躺著膨蛮,像睡著了一般。 火紅的嫁衣襯著肌膚如雪季研。 梳的紋絲不亂的頭發(fā)上敞葛,一...
    開封第一講書人閱讀 48,954評論 1 283
  • 那天,我揣著相機與錄音与涡,去河邊找鬼惹谐。 笑死,一個胖子當(dāng)著我的面吹牛驼卖,可吹牛的內(nèi)容都是我干的氨肌。 我是一名探鬼主播,決...
    沈念sama閱讀 38,271評論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼酌畜,長吁一口氣:“原來是場噩夢啊……” “哼儒飒!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起檩奠,我...
    開封第一講書人閱讀 36,916評論 0 259
  • 序言:老撾萬榮一對情侶失蹤桩了,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后埠戳,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體井誉,經(jīng)...
    沈念sama閱讀 43,382評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 35,877評論 2 323
  • 正文 我和宋清朗相戀三年整胃,在試婚紗的時候發(fā)現(xiàn)自己被綠了颗圣。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 37,989評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡屁使,死狀恐怖在岂,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情蛮寂,我是刑警寧澤蔽午,帶...
    沈念sama閱讀 33,624評論 4 322
  • 正文 年R本政府宣布,位于F島的核電站酬蹋,受9級特大地震影響及老,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜范抓,卻給世界環(huán)境...
    茶點故事閱讀 39,209評論 3 307
  • 文/蒙蒙 一骄恶、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧匕垫,春花似錦僧鲁、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,199評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至单芜,卻和暖如春蜕该,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背洲鸠。 一陣腳步聲響...
    開封第一講書人閱讀 31,418評論 1 260
  • 我被黑心中介騙來泰國打工堂淡, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人扒腕。 一個月前我還...
    沈念sama閱讀 45,401評論 2 352
  • 正文 我出身青樓绢淀,卻偏偏與公主長得像,于是被迫代替她去往敵國和親瘾腰。 傳聞我的和親對象是個殘疾皇子皆的,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 42,700評論 2 345

推薦閱讀更多精彩內(nèi)容