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

Mäkinen Jussi Jussi.Makinen at valtiokonttori.fi
Wed Jun 1 16:13:11 CEST 2005


Thanks Duncan,

For pointing this out. You maybe saved my day. I agree that these results are neither something I would like to see. I changed the code to be:

ifelse.o <- function (test, yes, no) 
{
    storage.mode(test) <- "logical"
    ans <- test
    nas <- is.na(test)
    if (any(test[!nas])) 
        ### Own change
	  ans[test & !nas] <- rep(yes, length.out = length(ans[test & !nas]))
    if (any(!test[!nas]))
	### Own change
        ans[!test & !nas] <- rep(no, length.out = length(ans[!test & !nas]))
	ans[nas] <- NA
    ans
}

which yields now

> x <- rnorm(10)
> ifelse.o(x > 0, 1:10, 0)
 [1] 1 2 0 3 0 4 0 5 6 0
> ifelse.o(x > 0, 0, 1:10)
 [1] 0 0 1 0 2 0 3 0 0 4

I'm even more happy now :-) I will anyway need to use this modificate function for just one specific problem. Hopefully there is no other hooks,

Jussi



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