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

From: <MSchwartz_at_mn.rr.com>
Date: Wed 22 Jun 2005 - 03:33:18 GMT


On Wed, 2005-06-22 at 04:46 +0200, wwl107@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?
>
> Thank you for your help.
>
> Woolton

This is not a bug and yes you have missed something.

Read R FAQ 7.31 Why doesn't R think these numbers are equal?

More information is also available here:

http://grouper.ieee.org/groups/754/

One possible solution:

> 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 [14] 0.00 0.13

> ifelse(sapply(i, function(x) all.equal(x, 0.33)) == "TRUE", 1, 0)
 [1] 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0

> ifelse(sapply(i, function(x) all.equal(x, 0.08)) == "TRUE", 1, 0)
 [1] 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0

> ifelse(sapply(i, function(x) all.equal(x, 0.2)) == "TRUE", 1, 0)
 [1] 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0

Marc Schwartz



R-devel@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel Received on Wed Jun 22 13:36:01 2005

This archive was generated by hypermail 2.1.8 : Mon 20 Feb 2006 - 03:21:09 GMT