[R] Logical operator fails to recognize vector element

Phil Spector spector at stat.berkeley.edu
Wed Oct 6 19:12:30 CEST 2010


Here's a simple example that might be instructive:

> x = 9.7900000001
> y = 9.79
> x
[1] 9.79
> y
[1] 9.79
> x == y
[1] FALSE
> abs(x - y) < 1e-8
[1] TRUE
> all.equal(x,y)
[1] TRUE

And as others have said, FAQ 7.31 .

 					- Phil Spector
 					 Statistical Computing Facility
 					 Department of Statistics
 					 UC Berkeley
 					 spector at stat.berkeley.edu



> On Wed, Oct 6, 2010 at 12:02 PM, D. Alain <dialvac-r at yahoo.de> wrote:
>> Hi experts,
>>
>> I have encountered a strange phenomenon after loading spreadsheet data via
>>
>>> example<-read.csv("M:\\...\\mydata.csv",header=T)
>>
>> My data consist of two variables x and y which I have combined to a single vector using
>>
>>> z<-rowSums(cbind(example$x,example$y))
>>> z
>> [1]  9.79  9.79 17.54 12.59  2.18  9.79         #vector z with 6 elements
>>
>> Now I want to identify all elements equal to 9.79, so I enter
>>
>>> which(z==9.79)
>>
>> And I get the result
>>
>> [1] 2 6                                                                 #R failes to identify the fist element!
>>
>> Taking a futher look at the elements I get the following:
>>
>>> mode(z)
>> [1] "numeric"
>>> mode(z[1])
>> [1] "numeric"
>>> z[1]+z[2]                                                             #I can add first and second element
>> [1] 19.58
>>
>> But if I try to apply logical operators I get:
>>
>>> z[1]==9.79
>> [1] FALSE
>>> z[2]==9.79
>> [1] TRUE
>>> z[1]==z[2]
>> [1] FALSE
>>
>> When I reenter the first element via
>>> z[1]<-9.79
>>> z[1]==9.79
>> [1] TRUE
>>
>> What is wrong with my data? Can anyone help?
>>
>>> version
>>               _
>> platform         i386-pc-mingw32
>> arch              i386
>> os                 mingw32
>> system          i386, mingw32
>> status
>> major             2
>> minor            11.1
>> year              2010
>> month           05
>> day               31
>> svn rev           52157
>> language        R
>> version.string  R version 2.11.1 (2010-05-31)
>>
>> Thanks
>> D. Alain
>>
>>
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>
>
>
> -- 
> Jim Holtman
> Cincinnati, OH
> +1 513 646 9390
>
> What is the problem that you are trying to solve?
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>


More information about the R-help mailing list