[英]R Shiny Server - how to keep variable value in observeEvent function?
[英]Call function, and return the value back to observeEvent in shiny app
我需要在 observeEvent 中調用 function(基於 select 輸入),我需要調用兩個函數,一個是獲取屬性名稱,另一個是獲取數據集名稱。 我只想知道如何在 observeEvent 中調用 function。
library(shiny)
library(shinydashboard)
ui<-
selectInput("select", "LPS tolerance induction:", c("", "LPS_Stim. at 0 h vs unstim" , "LOVE_Stim. at 20 h vs unstim",
"Restimulation (stim. at 0 h and 20 h vs unstim.)" ,
"Tolerance (stim. at 0 h and 20 h vs stim. at 20 h)"))
findattribute <- reactive({
if(grepl("LPS",input$select)){
x <- "val1"
return(x)
}
else if(grepl("LOVE", input$select)){
x <- "val2"
return(x)
}
else if(grepl("Res", input$select)){
x <- "val3"
return(x)
}
})
finddataset <- reactive({
if(grepl("LPS",input$select)){
x <- curated_lps # dataset name
return(x)
}
})
server<- function(input, output){
observeEvent(input$select, {
attribute <- findattribute()
dataset <- finddataset()
})
}
shinyApp(ui, server)
將反應器放在服務器中,如果沒有輸入未找到錯誤將發生。
請注意,在這種情況下, observeEvent
是多余的,因為findattribute()
和finddataset()
依賴於input$select
。 如果它們被包裹在isolate()
中,那么observeEvent()
就會有所作為。
server <- function(input, output, session) {
findattribute <- reactive({
if(grepl("LPS",input$select)){
x <- "val1"
return(x)
}
else if(grepl("LOVE", input$select)){
x <- "val2"
return(x)
}
else if(grepl("Res", input$select)){
x <- "val3"
return(x)
}
})
finddataset <- reactive({
if(grepl("LPS",input$select)){
x <- curated_lps # dataset name
return(x)
}
})
observeEvent(input$select, {
attribute <- findattribute()
dataset <- finddataset()
print(attribute)
print(dataset)
})
}
如果您需要將函數保留在服務器之外,您可以定義兩個函數,然后使用input$select
作為參數調用它們。
應用程序:
library(shiny)
library(shinydashboard)
curated_lps <- iris
ui <-
selectInput("select", "LPS tolerance induction:", c(
"", "LPS_Stim. at 0 h vs unstim", "LOVE_Stim. at 20 h vs unstim",
"Restimulation (stim. at 0 h and 20 h vs unstim.)",
"Tolerance (stim. at 0 h and 20 h vs stim. at 20 h)"
))
findattribute <- function(input){
if(grepl("LPS",input)){
x <- "val1"
return(x)
}
else if(grepl("LOVE", input)){
x <- "val2"
return(x)
}
else if(grepl("Res", input)){
x <- "val3"
return(x)
}
}
finddataset <- function(input){
if(grepl("LPS",input)){
x <- curated_lps # dataset name
return(x)
}
}
# SERVER ------------------------------------------------------------------
server <- function(input, output, session) {
observe({
attribute <- findattribute(input$select)
dataset <- finddataset(input$select)
print(attribute)
print(dataset)
})
}
shinyApp(ui, server)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.