输入与输出

案例研究:使用 R 的 Shiny 构建 Web 应用

Dean Attali

Shiny Consultant

输入

案例研究:使用 R 的 Shiny 构建 Web 应用

输入

chapter1_2_inputs_and_outputs.005.png

案例研究:使用 R 的 Shiny 构建 Web 应用

输入

chapter1_2_inputs_and_outputs.006.png

案例研究:使用 R 的 Shiny 构建 Web 应用

构建输入

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 构建 Web 应用

输出

  • 图、表、文本——任何 R 生成且用户可见的内容
  • 两步:

    1. 创建输出占位符(在 UI 中)

      ui <- fluidPage(
       "Plot goes here:",
       plotOutput(outputId = "my_plot")
      )
      
    2. 编写 R 代码生成输出(在 server 中)

案例研究:使用 R 的 Shiny 构建 Web 应用

服务器(server)

server <- function(input, output) {

  # Code for building outputs

}
  • input
    • 从此读取值(用户修改的输入)
  • output
    • 向此写入值(输出,如图表、表格)
案例研究:使用 R 的 Shiny 构建 Web 应用

构建输出

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 构建 Web 应用

Vamos praticar!

案例研究:使用 R 的 Shiny 构建 Web 应用

Preparing Video For Download...