輸入與輸出

案例研究:使用 R 的 Shiny 建置網頁應用程式

Dean Attali

Shiny Consultant

輸入

案例研究:使用 R 的 Shiny 建置網頁應用程式

輸入

chapter1_2_inputs_and_outputs.005.png

案例研究:使用 R 的 Shiny 建置網頁應用程式

輸入

chapter1_2_inputs_and_outputs.006.png

案例研究:使用 R 的 Shiny 建置網頁應用程式

建立輸入元件

ui <- fluidPage(
    textInput(inputId = "name", label = "Enter your name",
              value = "Dean"),
    numericInput(inputId = "sibs", label = "How many siblings?",
                 value = 4, min = 0)
)
  • 輸入函式:*Input(inputId, label, ...)
  • inputId = 唯一 ID
  • label = 輸入說明文字
  • ... = 其他輸入專屬參數
案例研究:使用 R 的 Shiny 建置網頁應用程式

輸出

  • 圖形、表格、文字——R 產生且使用者可見的任何內容
  • 兩個步驟:

    1. 建立輸出容器(在 UI)

      ui <- fluidPage(
       "Plot goes here:",
       plotOutput(outputId = "my_plot")
      )
      
    2. 撰寫 R 程式碼產生輸出(在 server)

案例研究:使用 R 的 Shiny 建置網頁應用程式

server 端

server <- function(input, output) {

  # Code for building outputs

}
  • input
    • 從這裡讀取值(使用者調整的輸入)
  • output
    • 寫入到這裡(輸出如圖形、表格)
案例研究:使用 R 的 Shiny 建置網頁應用程式

建立輸出

ui <- fluidPage(
    numericInput("num", "Number of rows", value = 10, min = 0),
    tableOutput("my_table")
)

server <- function(input, output) { output$my_table <- renderTable({ head(iris, n = input$num) }) }
  • 建立輸出物件的 3 條規則:
    1. 在 render 函式內建立物件(renderPlot()renderText() 等)
    2. 將物件儲存到 output$<outputId>
    3. input$<inputId> 取得輸入值
案例研究:使用 R 的 Shiny 建置網頁應用程式

一起來練習吧!

案例研究:使用 R 的 Shiny 建置網頁應用程式

Preparing Video For Download...