我正在编写一个闪亮的应用程序,它的输出应该依赖于变量的值,该变量是在一个反应性表达式中计算出来的。我相信我没有复制实际的应用程序,而是用以下简单的应用程序重新创建了我的问题:
ui.R file:
library(shiny)
shinyUI(pageWithSidebar(
headerPanel("Illustrating problem"),
sidebarPanel(
numericInput('id1', 'Numeric input, labeled id1', 0, min = 0, max = 100, step =5)
),
mainPanel(
h4('You entered'),
verbatimTextOutput("oid1"),
verbatimTextOutput("odic")
)
))
server.R file
library(shiny)
shinyServer(
function(input, output) {
output$oid1 <- renderPrint({input$id1})
x<-reactive({5*input$id1})
if (x()>50) output$oid2<-renderPrint({"You entered a number greater than 10"})
else output$oid2<-renderPrint({"You entered a number less than or equal to
10"})
}
)
如果我像这样运行它,那么我就会得到 .getReactiveEnvironment()$currentContext()
中的错误:.getReactiveEnvironment()$currentContext()
:‘
不允许在没有活动响应上下文的情况下进行操作。(您试图做一些只能在反应性表达式或观察者中完成的事情。)
如果我将If语句更改为:if (x>50)
..。然后我得到了错误:
X> 50中的错误:比较(6)只能用于原子类型和列表类型
当我将if语句更改为:if (reactive({(x>50)}))
..。然后我得到错误消息:
if中的错误(反应性({:参数不可解释为逻辑)
我非常感谢你的帮助
发布于 2016-01-15 23:48:31
几个问题。第一个也是最大的问题是,您似乎不了解反应性是如何工作的。错误上写着“没有活动的反应上下文就不允许操作”,这就是问题所在--您正在访问服务器函数的主体内的x()
,而不是在响应上下文中访问。例如,任何render*
函数都是一个反应性上下文。因此,要解决这个问题,您只需在renderPrint
中移动if语句。
另一个小问题是输出ids不匹配(verbatimTextOutput("odic")
与output$oid2
)。
如果你不理解反应性,我强烈建议你花半个小时来更好地理解它。This tutorial有一个关于反应性的章节,它可能很有帮助,或者您可以重新阅读RStudio发布的官方教程。
下面是您的固定应用程序的代码(我删除了一堆无用的UI元素)
library(shiny)
ui <- fluidPage(
numericInput('id1', 'Numeric input, labeled id1', 0, min = 0, max = 100, step=5),
verbatimTextOutput("oid1"),
verbatimTextOutput("oid2")
)
server <- function(input, output, session) {
output$oid1 <- renderPrint({input$id1})
x<-reactive({5*input$id1})
output$oid2<-renderPrint({
if (x()>50) {
"You entered a number greater than 10"
} else {
"You entered a number less than or equal to 10"
}
})
}
shinyApp(ui = ui, server = server)
发布于 2016-01-15 23:48:21
请注意,闪亮的工作是基于事件驱动模型的--几乎所有面向图形的UI都是这样做的(而今天,这是绝大多数)。它并不是一个新概念,至少从80年代开始就已经存在了,但它比遵循单一流程图的编程要复杂得多--确实需要一些习惯。
无论如何,在闪亮的reactive
、output
和observe
语句中,必须位于顶层,我不认为有例外。
你可能想要这样的东西:
library(shiny)
u <- shinyUI(pageWithSidebar(
headerPanel("Illustrating problem"),
sidebarPanel(
numericInput('id1', 'Numeric input, labeled id1', 0, min = 0, max = 100, step =5)
),
mainPanel(
h4('You entered'),
verbatimTextOutput("oid1"),
verbatimTextOutput("oid2")
)
))
s <- shinyServer(function(input, output) {
output$oid1 <- renderPrint({input$id1})
x<-reactive({5*input$id1})
output$oid2<-renderPrint({
if (x()>50){
"You entered a number greater than 10"
} else {
"You entered a number less than or equal to 10"
}
}
)
}
)
shinyApp(ui = u, server = s)
屈服:
https://stackoverflow.com/questions/34820952
复制相似问题