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

From: Mäkinen Jussi <Jussi.Makinen_at_valtiokonttori.fi>
Date: Thu 02 Jun 2005 - 00:13:11 EST


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



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Thu Jun 02 00:17:41 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:32:20 EST