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

Gabor Grothendieck ggrothendieck at gmail.com
Wed Jun 22 05:21:25 CEST 2005


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



More information about the R-devel mailing list