[Rd] ifelse behaviour

Duncan Murdoch murdoch at stats.uwo.ca
Thu Apr 26 16:05:15 CEST 2007


On 4/26/2007 9:53 AM, ml-it-r-devel at epigenomics.com wrote:
> Hi!
> 
> I'm puzzled by the return value of ifelse
> 
> consider
> 
> x<-integer(0)
> ifelse(is(x, "character"), paste(x), x)
> [1] NA

The test evaluates to a length 1 logical vector containing FALSE.  So 
ifelse() tries to return the first entry of x.  But x[1] doesn't exist, 
so it evaluates to NA, and that's what ifelse() returns.
> 
> whereas
> if (is(x, "character")) return(paste(x)) else x
> [1] integer(0)

This is quite different. It says to return the expression in the else 
clause, which is x.
> 
> or
> x<-integer(1)
> ifelse(is(x, "character"), paste(x), x)
> [1] 0
> 
> work as I had anticipated. Is this correct behaviour?

Yes, this is correct.

Duncan Murdoch



More information about the R-devel mailing list