1

Is there a vectorised mechanism to return a vector of a different shape to the test object in R's ifelse(test, yes, no) function?

The function is designed to return objects of the same shape as the test object:

> ifelse(TRUE, c(1, 3), 7)
[1] 1

But even if we get sneaky and try assigning objects so single length names are input, the result is the same:

> x <- c(1,3)
> ifelse(TRUE, x, 7)
[1] 1

The clunky control structure works:

> if(TRUE){c(1,3)}else{7}
[1] 1 3

But is there a vectorised way to achieve this?

[Edit: This is asking a different question to this one asking about inputting matrices, whereas this is asking about inputting vectors, even if the answer turns out to be similar. ]

Scransom
  • 3,175
  • 3
  • 31
  • 51
  • 1
    taking from SO answer below... you could wrap the vector with `list`, i.e `list(c(1,3))`. But as the post mentions, this is clunky. https://stackoverflow.com/questions/40340081/return-a-matrix-with-ifelse – D.sen Sep 06 '17 at 01:14

1 Answers1

1

1) if Normally one would just use a plain if in this case:

out <- if (TRUE) c(1, 3) else 7
out
## [1] 1 3

2) replace Another construct to consider is:

replace(c(1, 3), !TRUE, 7)
## [1] 1 3

3) ifelse / list If you really want to use ifelse this works:

ifelse(TRUE, list(c(1, 3)), list(7))[[1]]
## [1] 1 3
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341