反應式 101

使用 R 的 Shiny 建立網頁應用程式

Ramnath Vaidyanathan

VP of Product Research

一個讓使用者輸入姓名並回覆個人化問候的應用

使用 R 的 Shiny 建立網頁應用程式

反應式來源

透過瀏覽器介面進來的使用者輸入,通常為

ui <- fluidPage(
  titlePanel('Greeting'),

textInput('name', 'Enter Name')
) server <- function(input, output, session){ } shinyApp(ui = ui, server = server)
使用 R 的 Shiny 建立網頁應用程式

反應式終端

通常顯示在瀏覽器視窗中的輸出,例如圖表或數值表格。 `r

ui <- fluidPage( titlePanel('Greeting'), textInput('name', 'Enter Name'), textOutput('greeting') )


----CODE_GLUE----
```r
server <- function(input, output, session){

output$greeting <- renderText({ paste("Hello", input$name) })
}
使用 R 的 Shiny 建立網頁應用程式

反應式導體

介於中間的元件,依賴反應式來源,和/或更新反應式終端。

server <- function(input, output, session){
  output$plot_trendy_names <- plotly::renderPlotly({
    babynames %>% 
      filter(name == input$name) %>%
      ggplot(val_bnames, aes(x = year, y = n)) +
      geom_col() 
  })
  output$table_trendy_names <- DT::renderDT({
     babynames %>% 
      filter(name == input$name)
  })
}
使用 R 的 Shiny 建立網頁應用程式

反應式運算式

反應式運算式具有延遲快取特性。

server <- function(input, output, session){
  rval_babynames <- reactive({
    babynames %>% 
      filter(name == input$name)
  })
  output$plot_trendy_names <- plotly::renderPlotly({
     rval_babynames() %>%
      ggplot(val_bnames, aes(x = year, y = n)) +
      geom_col() 
  })
  output$table_trendy_names <- DT::renderDT({
     rval_babynames()
  })
}
使用 R 的 Shiny 建立網頁應用程式

一起來練習吧!

使用 R 的 Shiny 建立網頁應用程式

Preparing Video For Download...