Home > Mobile >  How can I use conditional to choose between two options or both?
How can I use conditional to choose between two options or both?

Time:11-14

I am building a shiny app and in a selectInput widget I want user to choose between options:

  • HRR, LRR, Both

The plot will change depending on user input and to correctly function:

if HRR -> return "HRR"

if LRR  -> return "LRR"

if Both -> return c("HRR", "LRR")

I want to apply this conditional using just one line. I have tried using ifelse but it returns an object of length the input:

ifelse(option == "Both", c("HRR", "LRR"), option)

But this will only ouput "HRR" when selected option is Both.

Thanks!

CodePudding user response:

This is because ifelse() will only return the first element (because it is a vectorized function - it expects input from a list of numbers). If you will only ever be using this when option is just a single value, then you can just use a normal if statement.

option <- "Both"
if(option == "Both") c("HRR", "LRR") else option

[1] "HRR" "LRR

If you want to use it with vector input you can just put that statement above in lapply().

option <- c("Both", "LRR", "HRR")
lapply(option, function(x) if(x == "Both") c("HRR", "LRR") else x)

[[1]]
[1] "HRR" "LRR"

[[2]]
[1] "LRR"

[[3]]
[1] "HRR"

  • Related