r - 查询和操作闪亮服务器中的变量
问题描述
我将继续尝试了解闪亮的基础知识。我现在尝试通过文本框 ( input$answer
) 获取用户输入,基于该输入 ( input$answer == "xyz"
) 进行条件测试,并根据该条件 ( if { <do stuff for correct answer> } else { <do stuff for incorrect answer> }
) 生成输出。
我想我已经掌握了很多基础知识。我可以获得用户输入,我已将其转换为反应值,因此我可以在 if 语句中生成查询而不会出错。我可以在提交答案后使用该用户输入生成输出。
不过有两个问题:
- 该查询
(isolate(input$answer) == "Hello")
永远不会为 TRUE,因为 的值isolare(input$answer)
始终保持为它最初分配的值。在当前情况下是“输入文本...”,但如果我将其留空,则行为不会改变(它只是假设“”作为值)。如果我将声明更改为if (isolate(input$answer) == "Enter text...")
评估将始终为 TRUE。为什么即使在随后paste0("Your answer of ",input$answer, " is incorrect!") })
的值被正确更新,这个值也不会改变? - 有没有办法在服务器启动时防止正确/不正确的评估,并且只有在第一次点击提交按钮时才启动它?
library(shiny)
#// Define UI for game ----
ui <- fluidPage(
#// for query
fluidRow (
#// column width and title
column(6, h3("Question"),
h4("Type the word `Hello`"),
#// Input: Text Box
textInput("answer", h3("Text input"),
value = "Enter text..."),
#// submit button to terminate the text input
submitButton("Submit")
), #// end column
#// column width and title
column(6, h3("Evaluation"),
#// Output: Text ----
textOutput(outputId = "evaluation")
) #// end column
) #// end fluidrow
) # end fluidpage
# Define server logic ----
server <- function(input, output) {
#// set up variables
answer <- reactiveValues()
#// logic for correct vs. incorrect
if (isolate(input$answer) == "Hello") {
#// correct counter up by one
correct <- correct + 1
counter <- counter + 1
#// answer is correct
output$evaluation <- renderText({
paste0("Your answer of `",input$answer, "` is correct!") })
} #// end if
else {
#// answer is not correct
output$evaluation <- renderText({
paste0("Your answer of `",input$answer, "` is incorrect!") })
counter <- counter + 1
} #// end else
#// stop app if count reaches number of games
if (counter == num) stopApp()
} #// end server
# Run the app ----
counter <- 0
num <- 10
shinyApp(ui = ui, server = server)
解决方案
当你从普通的 R 移动到 Shiny 时,你需要稍微改变你的逻辑。您想要响应的所有内容(即响应用户输入的更改)都需要在响应上下文中(例如 a renderText
)。
在此示例中,您的if
语句实际上仅在加载应用程序时执行一次。要让它更像你想要的那样工作,请尝试以下方式:
output$evaluation <- renderText({
if (input$answer == "Hello") {
#// correct counter up by one
correct <- correct + 1
counter <- counter + 1
paste0("Your answer of `",input$answer, "` is correct!")
} #// end if
else {
#// answer is not correct
counter <- counter + 1
paste0("Your answer of `",input$answer, "` is incorrect!")
} #// end else
})
在回答你的第二个问题时,我建议做两件事。第一个是在您的文本输入定义中更改value = "Enter text..."
为。placeholder = "Enter text..."
这将使应用程序知道“输入文本”不是真正的答案。然后,您可以req(input$answer)
在表达式的开头使用renderText
来停止执行,除非实际填写了文本字段。
推荐阅读
- xamarin - 如何将 Xamarin Forms 应用程序迁移到 GitHub?
- c# - 测试传递给 NEST (elasticsearch) 的参数
- javascript - 查询选择器返回 NULL
- angular - 找不到模块“./message.model”
- matlab - Matlab 指南从已经绘制的轴开始
- ecmascript-6 - lodash:按一个键进行主要排序,按另一个键进行次要排序
- php - Laravel 5.6 部署的应用程序路由给出 404 错误
- mongodb - 在 $lookup 中使用嵌套属性
- java - NullPointerException 获取休眠会话
- c - i386-elf-gcc:错误:spawn:没有这样的文件或目录