测试 R Shiny 中一组编号的输入对象中的任何输入是否为空 [英] Test whether any input in a set of numbered input objects in R Shiny is empty
问题描述
假设我为多图导出创建了 10 个 selectInput
下拉菜单,这些 selectInputs
被称为xaxis_1"、xaxis_2"、..... 、"xaxis_10"
Let's say I have created 10 selectInput
dropdowns for a multi plot export and these selectInputs
are called "xaxis_1", "xaxis_2", ..... , "xaxis_10"
对于单个 1 我可以写:if(!is.null(input$xaxis_1)) { .... do stuff }
当用户没有输入任何名称并按下提交时停止它运行导出,以避免崩溃.
for a single 1 I can write:
if(!is.null(input$xaxis_1)) { .... do stuff }
to stop it running export when the user hasn't entered any name, and presses submit, to avoid crashes.
更一般的你可以检查一下:
A bit more general you can check this:
if(!is.null(input[[paste('xaxis', i, sep = '_')]])) { ...}
如何优雅地编写它,以便 1 行代码检查 1:10 输入 [[...]] 中的任何一个是否为空,即 NULL?
how can you write it elegantly so that 1 line of code checks whether ANY of the 1:10 input[[...]] is empty, i.e. NULL?
输入的 nr 取决于用户想要导出每个文件的图数,所以所有都是用 lapply(1:input$nrofplots, function(i) { .... } renderUI
结构,而我的 if 语句需要具有 1:n 一样的灵活性
The nr of inputs depends on how many plots the user wants to export per file, so all is build with lapply(1:input$nrofplots, function(i) { .... } renderUI
structure, and my if statement needs to have the same flexibility of 1:n
在如下图所示的情况下,按 Initiate export
应该给出一个 sweetalert
(知道了)说至少缺少 1 个值
In a situation like below in the image, pressing Initiate export
should give a sweetalert
(got that covered) saying there is at least 1 value missing
推荐答案
这里是我在 UI 端用来验证用户输入的一个片段.
Here a snippet I used in the UI side to validate the user's inputs.
library(shiny)
library(shinyjs)
ui <- fluidPage(
useShinyjs(), # Set up shinyjs
numericInput('axis1','Val 1',1),
numericInput('axis2','Val 2',1),
numericInput('axis3','Val 3',1),
actionButton('Go','Plot')
)
server <- function(input, output, session) {
#Try 1, space, AAA and check what shiny will return
observe(print(input$axis1))
observe({
All_Inputs <- vapply(paste0('axis',1:3),
function(x){isTruthy(input[[x]])},
logical(1))
All_InputsCP <- all(All_Inputs)
shinyjs::toggleState(id="Go", condition = All_InputsCP) #This is to make the button Go able or disable according to condition All_InputsCP #
})
}
shinyApp(ui, server)
希望能帮到你.
这篇关于测试 R Shiny 中一组编号的输入对象中的任何输入是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!