Shiny 中的两个条件面板
Two conditionalPanel's in Shiny
我有一个 Shiny 应用程序,我创建了以下 conditionalPanel
:
conditionalPanel(condition="output.levels",
numericInput("centerpoints", "Number of center points", value=0, min=0, max=25)),
conditionalPanel(condition="!output.levels",
numericInput("centerpoints", "Number of center points", value=0, min=0, max=0))
如果 output.levels 为真,我想 select 在 0 到 25 个中心点之间。否则,中心点数必须为0。
问题是,如果条件为真,我 select 多于 0 个中心点,然后条件变为 FALSE,Shiny 保留之前 selected 的中心点,而不是 0。
有办法解决吗?
谢谢
您面临的问题来自于您的 ui 中有两个几乎相同的元素,它们共享相同的 ID。条件面板仅隐藏您的元素,但它们仍存在于文档中。所以你的第一个 numericInput
将永远是 Shiny 注册的那个,第二个不会绑定(即不会发送它的输入)到 Shiny 因为重复的 id。
我建议您以不同的方式实现这种情况。 Shiny 中有一些功能可以让您在应用程序全部设置好后更改一些现有的 ui 元素。这些函数是 updateXxxInput
,您可以更改相应输入元素中的任何变量。由于您唯一的目标是更改 numericInput
的 max
值,我们可以从服务器轻松完成此操作,我们可以在其中 observe
levels
或任何其他变量。在下面的代码中,我使用了一个简单的复选框。改变max
值的命令是updateNumericInput(session, "centerpoints", max = 0)
。请注意,这只会更改您输入的一个属性。与重新渲染 UI 元素相比,这是一个巨大的优势,因为您不必跟踪所有其他属性。
updateXxxInput
功能非常实用,赶快试试吧!
library(shiny)
ui <- shinyUI(
fluidPage(
numericInput("centerpoints", "Number of center points", value=0, min=0, max=25),
checkboxInput("changeCenterpoints", "Cap maximum at 0")
)
)
server <- function(input, output, session){
observeEvent(input$changeCenterpoints, {
if(input$changeCenterpoints){
updateNumericInput(session, "centerpoints", max = 0, value = 0)
}else{
updateNumericInput(session, "centerpoints", max = 25)
}
})
}
shinyApp(ui, server)
我有一个 Shiny 应用程序,我创建了以下 conditionalPanel
:
conditionalPanel(condition="output.levels",
numericInput("centerpoints", "Number of center points", value=0, min=0, max=25)),
conditionalPanel(condition="!output.levels",
numericInput("centerpoints", "Number of center points", value=0, min=0, max=0))
如果 output.levels 为真,我想 select 在 0 到 25 个中心点之间。否则,中心点数必须为0。
问题是,如果条件为真,我 select 多于 0 个中心点,然后条件变为 FALSE,Shiny 保留之前 selected 的中心点,而不是 0。
有办法解决吗? 谢谢
您面临的问题来自于您的 ui 中有两个几乎相同的元素,它们共享相同的 ID。条件面板仅隐藏您的元素,但它们仍存在于文档中。所以你的第一个 numericInput
将永远是 Shiny 注册的那个,第二个不会绑定(即不会发送它的输入)到 Shiny 因为重复的 id。
我建议您以不同的方式实现这种情况。 Shiny 中有一些功能可以让您在应用程序全部设置好后更改一些现有的 ui 元素。这些函数是 updateXxxInput
,您可以更改相应输入元素中的任何变量。由于您唯一的目标是更改 numericInput
的 max
值,我们可以从服务器轻松完成此操作,我们可以在其中 observe
levels
或任何其他变量。在下面的代码中,我使用了一个简单的复选框。改变max
值的命令是updateNumericInput(session, "centerpoints", max = 0)
。请注意,这只会更改您输入的一个属性。与重新渲染 UI 元素相比,这是一个巨大的优势,因为您不必跟踪所有其他属性。
updateXxxInput
功能非常实用,赶快试试吧!
library(shiny)
ui <- shinyUI(
fluidPage(
numericInput("centerpoints", "Number of center points", value=0, min=0, max=25),
checkboxInput("changeCenterpoints", "Cap maximum at 0")
)
)
server <- function(input, output, session){
observeEvent(input$changeCenterpoints, {
if(input$changeCenterpoints){
updateNumericInput(session, "centerpoints", max = 0, value = 0)
}else{
updateNumericInput(session, "centerpoints", max = 25)
}
})
}
shinyApp(ui, server)