How to custom order values in a selectInput widget

Hello,
I have a Shiny selectInput widget that pulls unique injury severity values from a column in a data.table. It looks like this:
unique(testdata$INJ_SVRTY_NEW)

[1] "Major Injury" "Property Damage Only" "Serious Injury" "Minor Injury"
[5] "Fatal" "Unknown" `

I would like the values to be listed in the selectInput drop down in a certain order that is not "ascending" or "decending". Rather, I wish to have it defined by severity, such as "Fatal", "Serious", "Major", etc.

I have thought about assigning a key value and using that to re-order, but not sure that's the best way... or perhaps do I simply create a new object like orderInjSev <- c("Fatal","Serious Injury", "Major Injury") and then use order and match to re-order?

What would be the most efficient way of coding a solution for this? Thanks!

The values will be listed in whatever order you provide them. unique does not sort them.

One way would be to use a factor.

possible_values <- c("Fatal", "Serious Injury", "Major Injury")
ordered_values <- factor(unique(testdata$INJ_SVRTY_NEW), levels = possible_values)

Yes, many thanks @woodward - this works. I appreciate the contribution.

1 Like

@woodward - Well, I think you're on the right track here, factor assigns a number value to the character value, per the defined possible_values:

[1] Minor Injury Major Injury Serious Injury
[5] Fatal
Levels: Fatal Serious Injury Major Injury Minor Injury Unknown

The levels are defined correctly, based on the sequence defined for "possible_values" but the "ordered_values" object is not behaving as it should because this what get pulls into the selectInput widget:

Annotation 2020-06-18 123127

Note the list is not even in the correct sequence.

Question 1: How to get the sequence correctly ordered?
Question 2: How to match the factor values to the character value and return the character in the list?

You probably want to use possible_values in your selectInput. You can add additional values like "All" or "Missing Data" even though these are not in the data.

1 Like

@woodward - yes, that's what I ended up doing and it seemed to work ok. Thank you!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.