0

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
J.Sabree
  • 2,280
  • 19
  • 48
  • There's a typo in `... unique(mtcars$vs), vs_paramter)` `vs_paramter` != `vs_parameter ` – Andre Wildberg Mar 04 '23 at 19:32
  • if you have a look at `help(ifelse)`: ifelse returns a value with the **same shape** as test which is filled with elements selected from either yes or no depending on whether the element of test is TRUE or FALSE. test has one element, so does the result – Waldi Mar 04 '23 at 19:35
  • @Waldi, is there a way around this or another function you'd recommend? and thanks andre, I fixed the typo – J.Sabree Mar 04 '23 at 19:37
  • See here https://stackoverflow.com/questions/9449184/if-else-vs-ifelse-with-lists – Andre Wildberg Mar 04 '23 at 19:41

1 Answers1

1

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 values(s).

ifelse(vs_parameter == "all", 
       paste(unique(mtcars$vs), collapse = " "), 
       vs_parameter)
# [1] "0 1"
Jon Spring
  • 55,165
  • 4
  • 35
  • 53
  • Your first solution is good; the second one isn't. It will give the wrong answer if `vs_parameter` has length greater than 1. – user2554330 Mar 04 '23 at 20:43
  • "However, if they specify an actual value, it should give that value." When I run with `vs_parameter = 2:3)`, I get output of `[1] 2 3`. What do you think the OP would want there? – Jon Spring Mar 04 '23 at 21:33
  • Sorry, I was probably wrong. But if `vs_parameter = c("all", "none")` it would do weird things. As would the first, of course. – user2554330 Mar 04 '23 at 22:42