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 :
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"