開始使用免費開始

反應式情境(Reactive contexts)

在 Shiny 裡,reactive 值是特殊的結構;在 R 程式設計的其他地方看不到。因此,它們不能在任意的 R 程式碼中使用,reactive 值只能在「反應式情境」中被存取。

這也是為什麼只要有變數依賴 reactive 值,就「必須」用 reactive() 函式建立,否則會發生錯誤。Shiny 的 server 本身不是反應式情境,但 reactive() 函式、observe() 函式,以及所有 render*() 函式都是。

本練習屬於課程

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

檢視課程

練習說明

你會拿到一個包含兩個數值輸入 num1num2,以及一個文字輸出的 Shiny 應用。你的任務是:

  • 在名為 my_sum 的反應式變數中,計算兩個數值輸入的加總(第 10 行)。
  • 在名為 my_average 的反應式變數中,計算兩個輸入的平均(第 14 行)。
  • 在文字輸出中,使用這些反應式變數來顯示計算出的平均值(第 23 行)。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

ui <- fluidPage(
  numericInput("num1", "Number 1", 5),
  numericInput("num2", "Number 2", 10),
  textOutput("result")
)

server <- function(input, output) {
  # Calculate the sum of the inputs
  my_sum <- reactive({
    input$num1 + ___
  })

  # Calculate the average of the inputs
  my_average <- ___({
    my_sum() / 2
  })
  
  output$result <- renderText({
    paste(
      # Print the calculated sum
      "The sum is", my_sum(),
      # Print the calculated average
      "and the average is", ___
    )
  })
}

shinyApp(ui, server)
編輯並執行程式碼