[R] A suggestion to improve ifelse behaviour with vector yes/noarguments

Duncan Murdoch murdoch at stats.uwo.ca
Wed Jun 1 13:12:47 CEST 2005


Mäkinen Jussi wrote:

> Hello,
> 
> I'm happy with the modified ifelse:
> 
> ifelse.o <- function (test, yes, no) 
> {
>     storage.mode(test) <- "logical"
>     ans <- test
>     nas <- is.na(test)
>     if (any(test[!nas])) 
>         ans[test & !nas] <- rep(yes, length.out = length(ans))[test & 
>             !nas]
>     if (any(!test[!nas])) 
> 		### Changed
>         ans[!test & !nas] <- rep(no, length.out = length(ans[!test & !nas]))
>     ans[nas] <- NA
>     ans
> }

I wouldn't be:

 > x
  [1] -0.4539550 -1.3023478  0.9034912  1.7485065  0.6910265 -0.7712547
  [7] -0.6345585  1.8296632  2.1207810  0.7643834
 > ifelse.o(x > 0, 1:10, 0)
  [1]  0  0  3  4  5  0  0  8  9 10
 > ifelse.o(x > 0, 0, 1:10)
  [1] 1 2 0 0 0 3 4 0 0 0

I'd call these results fairly perverse.

Duncan Murdoch




More information about the R-help mailing list