我有一个R Shiny应用程序,我想让它在Shiny App中将字段保留为空白时自动使用Shiny调用的函数的默认值。我提供了一个简单的示例,其中Shiny App正在调用该函数printFun
。我希望它能正常工作,例如,如果用户未b
在Shiny应用程序中输入的值,则该函数将识别为2
默认值。但是,如果保留为b
空白,则不会将任何值传递给该函数。
在Shiny中,有没有其他选项可以处理此类默认设置?在此先感谢您的帮助。
library(shiny)
# simple example of function
printFun <- function(a = 1, b =2, c =3, d = 4){
printVal <- paste0(
"one = ", a, "\n",
"two = ", b, "\n",
"three = ", c, "\n",
"four = ", d, "\n"
)
cat(printVal)
}
# ui function
ui <- fluidPage(
textInput("a", "a value"),
textInput("b", "b value"),
textInput("c", "c value"),
textInput("d", "d value"),
actionButton("runFun", "run function")
)
# server function
server <- function(input, output){
observeEvent(input$runFun, {
printFun(
a=input$a,
b=input$b,
c=input$c,
d=input$d
)
})
}
shinyApp(ui = ui, server = server)
这是一种方法
server <- function(input, output){
observeEvent(input$runFun, {
vals <- Map(function(x) input[[x]], c("a","b","c","d"))
vals <- Map(as.numeric, vals)
vals <- Filter(function(x) !is.na(x), vals)
do.call("printFun", vals)
})
}
基本上,我们Map
获取所有值并将其转换为数字。然后,我们过滤掉不是数字的值。我们需要执行此操作,因为您有文本输入,当这些文本输入为空时,您可能希望忽略它们。现在,我们有了用户提供的值的列表,可以使用传递给函数do.call
。
您也可以将默认值添加到文本输入本身。
ui <- fluidPage(
textInput("a", "a value", value=formals(printFun)[["a"]]),
textInput("b", "b value", value=formals(printFun)[["b"]]),
textInput("c", "c value", value=formals(printFun)[["c"]]),
textInput("d", "d value", value=formals(printFun)[["d"]]),
actionButton("runFun", "run function")
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句