【发布时间】:2019-09-03 11:12:51
【问题描述】:
我正在开发一个基于 R Shiny 的应用程序。 我想让我的输入与可用数据保持一致,因此我更新了 selectInput 中的选定值。 当我更改输入 1 中的选定值时,输入 2 的值会更新,然后数据会更新(仅一次)。好的 但是,如果我更改输入 2 中的选定值,则更新数据,然后更新输入 1 的值,然后再次更新数据。 查看打印两次的“check latest_value”。
最初我使用的是 renderUI 而不是 updateSelectInput,但在初始化时,数据被计算了两次。
library(shiny)
library(DT)
library(dplyr)
my_data=data.frame(CO2)
# Running a Shiny app object
app <- shinyApp(
ui = bootstrapPage(
selectInput('type','Choix du type',choices = unique(my_data$Type)),
uiOutput('plant_ui'),
DTOutput('plot')
),
server = function(input, output) {
data=reactive({
# req(input$type)
my_data_temp=my_data
if(length(input$type)>0){
my_data_temp=my_data_temp%>%filter(Type%in%input$type)
}
if(length(input$plant)>0){
my_data_temp=my_data_temp%>%filter(Plant%in%input$plant)
}
my_data_temp
})
latest_plant_value=reactive({
if(is.null(input$plant))data()$Plant[1]
else input$plant
})
output$plant_ui=renderUI({
sub_data=data()
selectInput(inputId = 'plant',"filtre par plant",choices = unique(sub_data$Plant),
selected=latest_plant_value())
})
output$plot <- renderDT({
print("check latest_value")
datatable(data()) })
}
)
runApp(app)
这就是为什么我决定基于 Alternate control of a sliderInput between a derived value and user selected value 使用 updateSelectInput,但是代码的顺序结构使得当我更改输入 2 值时要计算两次数据。
library(shiny)
library(DT)
library(dplyr)
my_data=data.frame(CO2)
# Running a Shiny app object
app <- shinyApp(
ui = bootstrapPage(
selectInput('type','Choix du type',choices = unique(my_data$Type),selected=my_data$Type[1]),
selectInput('plant','Choix du type',choices = unique(my_data$Plant),selected=my_data$Plant[1]),
DTOutput('plot')
),
server = function(input, output,session) {
data=reactive({
# req(input$type)
my_data_temp=my_data
if(length(input$type)>0){
my_data_temp=my_data_temp%>%filter(Type%in%input$type)
}
if(length(input$plant)>0){
my_data_temp=my_data_temp%>%filter(Plant%in%input$plant)
}
my_data_temp
})
observeEvent(input$type,{
print("update type changed")
updateSelectInput(session, "plant",
selected = unique(my_data%>%filter(Type%in%input$type)%>%.$Plant)[1])
})
observeEvent(input$plant,{
print("update plant changed")
updateSelectInput(session, "type",
selected = unique(my_data%>%filter(Plant%in%input$plant)%>%.$Type)[1])
})
output$plot <- renderDT({
print("check latest_value")
datatable(data()) })
}
)
runApp(app)
这样的修复在这种情况下不起作用,因为我不想达到同样的目的three interdependent selectInput in R/Shiny application
我希望每个输入的默认选择值保持一致,以便过滤器返回至少 1 个值。这是我更改的任何输入。
【问题讨论】:
-
你试过用
isolate()吗?
标签: r input shiny selectinput