mardi 5 septembre 2017

Return vector of length n to test of length 1, (or different shape from test) with vectorised ifelse?

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 better, vectorised way?

Aucun commentaire:

Enregistrer un commentaire