four-eyes
four-eyes

Reputation: 12385

If/else statement does not evaluate properly shiny/R

Working with shiny for R.

In my ui.R I have an element looking like this

radioButtons("startEnd",
    label = "Choose",
    choices = list("start" = 1,
    "end" = 2),
    selected = NA,
    inline = TRUE
) 

In my server.R I have this

observeEvent(input$startEnd, {
    print(input$startEnd)
    if (!is.null(as.integer(input$startEnd)) == 1) {
            print("Gone in if")
    } else if (!is.null(as.integer(input$startEnd)) == 2) {
            print("Gone in else if")
    } else {
            print("Gone in nothing")
    }       
}) 

However, it always evaluates to print("Gone in if"). BUT my first print(input$startZiel) prints me the correct numbers, depending on what I clicked in the app.

Upvotes: 0

Views: 292

Answers (1)

James Elderfield
James Elderfield

Reputation: 2507

What you are currently doing is converting input$startEnd to an integer, converting that integer to a boolean by negating its nullness, and then comparing that boolean to an integer. Because your numbers are not null, the boolean evaluates to TRUE which is equal to 1 and so the first condition always holds. I think what you want is in fact the following,

observeEvent(input$startEnd, {
print(input$startEnd)
asInt = as.integer(input$startEnd)
if(!is.null(asInt)) {
    if (asInt == 1) {
        print("Gone in if")
    } else if (asInt == 2) {
        print("Gone in else if")
    } else {
        print("Gone in nothing")
    }  
}     

})

Upvotes: 2

Related Questions