tumultous_rooster
tumultous_rooster

Reputation: 12550

Returning integer values from RadioButton in Shiny

I created some radio buttons in Shiny; however, I am wondering if there is a way to have the returned value be an integer, and not character.

Wanting integers came up in the context of a RadioButton being used to select gender.

When I do:

radioButtons(inputId="gender", "Gender", choices = list("combined" = 0, "male" = 1, "female" = 2)

I find that

print(str((input$gender)))

gives me

chr "0" 

I know I can change this within the server:

gender <- as.integer(input$gender)

but I'm trying hard to clean up that code by cutting lines down.

Is there any way I change the output type within the UI?

Upvotes: 7

Views: 2052

Answers (1)

clemens
clemens

Reputation: 6813

The documentation of the argument 'choices' of the function radioButtons() says 'The values should be strings; other types (such as logicals and numbers) will be coerced to strings.' If you use the arguments choiceNames and choiceValues instead of choices, normalizeChoicesArgs() within radioButtons() will once again coerce the values to character (which is true for other inputs like checkboxGroupInput() as well).

Since you define a list in your choices that will always return either "0", "1", or "2", it is safe to coerce the values to a numeric data type in the server function of the shiny app.

Upvotes: 2

Related Questions