From ggrothendieck at gmail.com  Wed Jun 22 05:21:25 2005
From: ggrothendieck at gmail.com (Gabor Grothendieck)
Date: Tue, 21 Jun 2005 23:21:25 -0400
Subject: [Rd] Trouble with ifelse and if statement (PR#7962)
In-Reply-To: <20050622024649.D4BEEA22C@slim.kubism.ku.dk>
References: <20050622024649.D4BEEA22C@slim.kubism.ku.dk>
Message-ID: <971536df050621202119353873@mail.gmail.com>

On 6/21/05, wwl107 at psu.edu <wwl107 at psu.edu> wrote:
> Full_Name: Woolton Lee
> Version: 2.1
> OS: windows
> Submission from: (NULL) (128.118.224.46)
> 
> 
> I did the following ('g' and 'h' are both numeric vectors)
> > i <- abs(g-h)
> creating a vector 'i' with values,
> > i
>  [1] 0.08 0.00 0.33 0.00 0.00 0.00 0.00 0.33 0.00 0.00 0.08 0.08 0.20 0.00 0.13
> 
> Now, I want to create a new vector =1 whenever 'i' = 0.33 and =0 otherwise.  I
> use the 'ifelse' function to do this but when I do, I find
> > ifelse(i==0.33,1,0)
>  [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
> 
> even though the third and eighth elements of 'i' clearly equal 0.33.  Unless I
> have missed something, 'ifelse' should return a vector that looks like,
> [1] 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0
> 
> When I try 0.13 I get a correct result
> > ifelse(i==0.13,1,0)
>  [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
> 
> but when I try 0.08 or 0.2 I find a similar problem,
> > ifelse(i==0.08,1,0)
>  [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
> > ifelse(i==0.20,1,0)
>  [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
> > ifelse(i==0.2,1,0)
>  [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
> 
> Can you explain what is happening?  Why is R incorretly returning a vector that
> does not reflect the values in 'i'?  Is this due to a malfunction in R or have I
> missed something?

This is 7.31 of the R FAQ:

http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-doesn_0027t-R-think-these-numbers-are-equal_003f



[Rd] Trouble with ifelse and if statement (PR#7962)
Gabor Grothendieck