shiny - 访问 eventReactive 中的值
问题描述
我需要一个基本的 Shiny 问题的帮助。我的目标是制作一个简单的数学测验应用程序(什么是 4 x 4?)。我想用一个按钮创建值,选择一个数字答案,然后按另一个答案按钮。我的问题是我找不到访问存储在 eventReactive 中的值的方法。我在下面的代码中简化了问题。这个应用程序的目标是要求一个号码,然后提供它。先感谢您!
# Goal: Fetch a number, then input that number, then receive paste("correct")/paste("incorrect)
ui <- fluidPage(
textOutput(outputId = "out"),
numericInput(inputId = "inn",
label = "",
value = 0),
actionButton("answer", "Answer"),
actionButton("question", "New Question"),
)
server <- function(input, output) {
data <- eventReactive(input$question,{
a <- sample.int(10,1)
paste("Enter",a)
})
output$out <- renderText({data()})
}
shinyApp(ui,server)
解决方案
这是我会做的
ui <- fluidPage(
textOutput(outputId = "out"),
numericInput(inputId = "inn", label = "", value = 0),
actionButton("answer", "Answer"),
actionButton("question", "New Question"),
)
server <- function(input, output, session) {
data <- reactiveValues(number = NULL)
output$out <- renderText({
if (is.null(data$number))
"Press 'New Question' button"
else
paste("Enter", data$number)
})
observeEvent(input$question, {
data$number = sample(10, 1)
})
observeEvent(input$answer, {
req(data$number, input$inn)
if (data$number == input$inn)
print("Correct")
# Do something exciting
else
print("Incorrect")
# Do something else
})
}
shinyApp(ui,server)
IMO 将反应数据和输入/输出生成分开是一种很好的做法。我的意思是在上面的例子中我们使用
reactiveValues
跟踪不断变化的数据,以及observeEvent
监控可能会改变我们反应数据的特定元素的按钮点击,renderText
可以打印固定文本或反应数据。
推荐阅读
- visual-studio - Xamarin.Forms 中的空应用程序不起作用
- python-3.x - Xgboost Amazon Sagemaker 网格搜索替代方案
- python - 从 pandas groupby 获取四分位距和中位数,所有未提及日期的零填充
- c# - 使用依赖注入时的消息分区器?
- java - Tableview没有在列中设置正确的信息
- google-apps-script - 提示工作表中的范围以清除文本但保留公式
- javascript - 即使在使用 beginPath() 和 Closepath() 之后,在画布上绘图时也无法为 fillStyle 使用不同的颜色
- c# - 无法在 Visual Studio 中将程序集引用 (dll) 添加到 AWS Lambda 函数项目
- excel - 如果其他单元格包含特定文本,则将特定单元格的总和放入一个单元格
- tensorflow - 张量流中的降维API