Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does ifelse in R not give the TRUE output?

I have a very simple ifelse() statement. With the mtcars dataset, I want to define a parameter for the vs column. If the user says "all", then it should give all unique values (0 and 1, here). However, if they specify an actual value, it should give that value. Though the false condition works, the TRUE condition does not. Why not?

library(dplyr)
data("mtcars")

vs_parameter <- c("all")

ifelse(vs_parameter == "all", unique(mtcars$vs), vs_parameter)

#but if you change vs_parameter <- c(1), it does work

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ifelse in R is different from if() {} else {}. I think you want the latter:

if(vs_parameter == "all") {
  unique(mtcars$vs)
} else(
  vs_parameter
)

As Waldi noted, ifelse takes the "shape" of test — in this case, a boolean vector of length 1 — and outputs in the same shape. The first element of unique(mtcars$vs) is 0 so that’s what you get as output.

Alternatively, you could coerce the output to be length one, so that you get all the unique values as a concatenated string, or else the input value.

ifelse(vs_parameter == "all", 
       paste(unique(mtcars$vs), collapse = " "), 
       vs_parameter)
# [1] "0 1"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading