[英]How to create IF statement with reactive values in R ( Shiny )
初學者到R,在這里閃亮! 試圖做一個最小的工作示例......我想檢查一個無功輸入值的條件。 我究竟做錯了什么?
library(shiny)
ui<-fluidPage(
numericInput(inputId="a", label=NULL, value=0),
textOutput(outputId="out")
)
server <- function(input, output) {
x <- reactive(input$a)
if (x() < 4)
{y<-1}
else
{y<-0}
output$out <- renderText({y})
}
shinyApp(ui = ui, server = server)
錯誤消息:
沒有活動的反應上下文,不允許操作。 (你試圖做一些只能在反應式表達式或觀察者內部完成的事情。)
你只需要對你的if
使用reactive
,以便閃亮知道y
在x
會發生變化。
library(shiny)
ui<-fluidPage(
numericInput(inputId="a", label=NULL, value=0),
textOutput(outputId="out")
)
server <- function(input, output) {
x <- reactive(input$a)
y <- reactive( if (x()<4) 1 else 0 )
output$out <- renderText({ y() })
}
shinyApp(ui = ui, server = server)
John Paul的上述答案當然是可以接受的,但我認為你可能希望看到另一種方式作為你學習過程的一部分。 我會讓StackOverflow排除哪個更合適。
library(shiny)
ui<-fluidPage(
numericInput(inputId="a", label=NULL, value=0),
textOutput(outputId="out")
)
server <- function(input, output) {
state <- reactiveValues()
observe({
state$x <- input$a
state$y <- ifelse(state$x < 4, 1, 0)
})
output$out <- renderText({ state$y })
}
shinyApp(ui = ui, server = server)
這是我的嘗試。 1)如上所述,您不需要在反應上下文中包含輸入$ a並另存為x。 只需使用輸入$ a 2)在這個簡單的例子中你不需要reactiveValues。 只需將y保存為反應變量。 然后,在renderText中,通過調用函數(“y()”)進行訪問
library(shiny)
ui<-fluidPage(
numericInput(inputId="a", label=NULL, value=0),
textOutput(outputId="out")
)
server <- function(input, output) {
y <- reactive({
if (input$a < 4) {
return(1)
} else {
return(0)
}
}
)
output$out <- renderText({y()})
}
shinyApp(ui = ui, server = server)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.