Shiny应用添加Radio Button报错:argument is of length zero的原因与解决
Hey there, let's break down what's causing that error and how to fix it quickly.
错误原因
The problem comes from how you tried adding the radio button component directly into the questions list. The shinyforms package expects every item in the questions list to be a structured list with specific properties (like id, type, title, etc.), not a raw Shiny UI element like radioButtons().
When you uncomment that line with radioButtons(), you're inserting an object that doesn't have an id property in the way shinyforms expects. When the package tries to check if question$id %in% fieldsMandatory, it gets a NULL value for question$id, which makes the condition have length zero—hence the error you're seeing.
解决办法
Instead of using Shiny's native radioButtons() function, define your radio button question using the format that shinyforms understands. For radio inputs, set the type to "radio" and add a choices property to list your options.
Here's the corrected version of your questions list with the gender radio button properly integrated:
questions <- list( list(id = "name", type = "text", title = "Name", mandatory = TRUE), list(id = "age", type = "numeric", title = "Age", mandatory = TRUE), list(id = "Income", title = "Your average annual income from all sources before tax (e.g. Pension, employment, investments, etc.) is", type = "text", mandatory = TRUE), list(id = "saving", type = "text", title = "You regularly save the following percentage of your income for special expenditures, such as education, mortgage lump sum repayments, retirement, etc", mandatory = TRUE), list(id = "continue", title = "You expect your current income level (at a minimum) to continue for the:", type = "text", mandatory = TRUE), list(id = "status", type = "text", title = "You would describe your financial situation as being:", mandatory = TRUE), # Properly formatted radio button question for shinyforms list( id = "gender", type = "radio", title = "Select your Gender", choices = c("Male" = 1, "Female" = 2), selected = 1, mandatory = TRUE # Optional: set to TRUE if this is a required field ), list(id = "correct", type = "checkbox", title = "I have given correct answers") )
关键修改点:
- We replaced the raw
radioButtons()call with a list that includesid,type = "radio",title,choices, and optionalselected/mandatoryproperties. - This matches the structure of all other questions in your list, so
shinyformscan process it correctly without hitting theargument is of length zeroerror.
Once you make this change, your app should run smoothly and save the gender selection to your Excel file just like the other fields.
内容的提问来源于stack exchange,提问作者YOGESH RAO

