始める無料で始める

eventReactive() で反応を遅らせる

Shiny のリアクティブプログラミングは、入力が変わると、それに依存する出力が自動的に更新されるように設計されています。ですが、状況によっては、更新の引き金となるタイミングを明示的に制御したいことがあります。

eventReactive() は、特定のイベントが発生したときにだけ更新されるリアクティブ値を計算するための関数です。

rval_x <- eventReactive(input$event, {
 # 計算処理
})

この演習はコースの一部です

Rで作るShiny Webアプリケーション

コースを見る

演習の手順

  • eventReactive() を使って、ユーザーがボタンをクリックするまで BMI の計算を実行しないようにしましょう。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

ui <- fluidPage(
  titlePanel('BMI Calculator'),
  sidebarLayout(
    sidebarPanel(
      textInput('name', 'Enter your name'),
      numericInput('height', 'Enter height (in m)', 1.5, 1, 2, step = 0.1),
      numericInput('weight', 'Enter weight (in Kg)', 60, 45, 120),
      actionButton("show_bmi", "Show BMI")
    ),
    mainPanel(
      textOutput("bmi")
    )
  )
)

server <- function(input, output, session) {
  # MODIFY CODE BELOW: Use eventReactive to delay the execution of the
  # calculation until the user clicks on the show_bmi button (Show BMI)
  rval_bmi <- reactive({
    input$weight/(input$height^2)
  })
  output$bmi <- renderText({
    bmi <- rval_bmi()
    paste("Hi", input$name, ". Your BMI is", round(bmi, 1))
  })
}

shinyApp(ui = ui, server = server)
コードを編集して実行