R闪亮-基于列表的条件面板



是的,有许多问题措辞非常相似,例如

r shiny - conditionalPanel with condition:检查列表中的项目或条件面板中的多个条件r shiny

没有,然而,似乎排序的问题-另外似乎是一个js语法比R正确。

考虑以下MRE:

library(shiny)
collective <- c("happiness","love","peace","time","foo","bar")
numerable <- c("apple","orange","banana","quux","baz","bob")
ui <- fluidPage(

selectInput("choice","choose one",choices=c(collective,numerable)),

conditionalPanel(
condition = TRUE, ## This is the condition I need to write !
numericInput("number",
"How many?",
value=3)
),


textOutput("result")
)
server <- function(input, output, session) {

output$result <- renderText({

if(is.null(input$number)){
paste("You want some", input$choice)
}else{
paste("you want",input$number,input$choice)
}
})
}
shinyApp(ui = ui, server = server)

这里我想只在用户选择可以计数的东西时才显示数字框。

在纯R中,我将把我的条件写成if(input$choice %in% numerable)……等。

但是此时条件必须用js写。

因此,问题是,我如何将这个R语句转换成在这个上下文中工作的js条件

?类似的问题得到了以下答案,或者可能是解决方法:

1)使用renderUI代替,它可以在R中这样编码:

output$numberUI <- renderUI({
if( input$choice %in% numerable) {
# pass
}else{
numericInput("number",
"How many?",
value=3)
}
})

,用uiOutput("numberUI")替换条件面板。这确实有效,事实上这就是我现在在我的"真实"中所做的app,但是我发现结果代码可读性较差,UI定义分散在UI和服务器之间。

2)明确列出所有可能的情况condition = "input.choice == 'apple' || input.choice =='orange' || input.choice == 'banana' " ...等,这显然是笨拙和容易出错(此外,如果numerable的列表是数据驱动的,在我的情况下,它是在基于names(the_data)的实际应用程序中不起作用)。

我很确定js有一个运算符相当于R的%在%所以问题归结为我如何翻译这个R语句:input$choice %in% numerable到js ?明显的"input.choice in numerable"不起作用,大概是因为我首先需要将numerable转换为js对象?

编辑:根据斯特文森·洛朗的数据我意识到当然条件是一个字符串,所以没有什么能阻止我动态地创建条件字符串. 所以:

condition = paste('[',paste(paste('"',numerable,'"',sep=''),collapse=','),'].includes(input.choice)',sep='')

…如果有些不可读(可以使用管道,glue等进行美化)可以完成工作。

Try

condition = '["apple","orange","banana","quux","baz","bob"].includes(input.choice)'

condition = '["apple","orange","banana","quux","baz","bob"].indexOf(input.choice) > -1'

最新更新