[R] what don't I get about numeric/double comparisons in R way?

Peter Ehlers ehlers at ucalgary.ca
Thu Dec 31 07:06:50 CET 2009


donahchoo at me.com wrote:
> 
> On Dec 30, 2009, at 10:10 PM, Jim Lemon wrote:
> 
>> On 12/31/2009 02:41 PM, donahchoo at me.com wrote:
>>> Hi,
>>>
>>> I'm pretty much an R noob and I'm missing some paradigm in R I 
>>> think.  I can't figure our how to compare numerics.  here's a 
>>> transcript of my tests.  Any pointers?
>> Hi donahchoo,
>> You're comparing the printed value of range_sd, which has been 
>> truncated, to the actual value. As the printout says, the difference 
>> is small, but present. If you set range_sd to the printed value:
>>
>> range_sd<-34.40783
>>
>> the comparisons will return TRUE.
>>
>> Jim
>>
> 
> Thanks, Jim.  I figured this out after sending the email, but I still 
> can't compare. Here's some more tests, note that all.equal returns true 
> but so does !=
> 
> actual_mean <- mean( range)
> actual_sd <- sd( range)
> expected_mean <- 218.213483146067
> expected_sd <- 159.277118043936
> print(paste("expected_mean", expected_mean))
> print(paste("actual_mean", actual_mean))
> print(paste("expected_sd", expected_sd))
> print(paste("actual_sd", actual_sd))
> 
> if( expected_mean != actual_mean ) {
>   stop( "not equal" )
> }
> 
> Output:
> 
>  > source("/Users/adhamh/Developer/r/test.r")
> [1] "expected_mean 218.213483146067"
> [1] "actual_mean 218.213483146067"
> [1] "expected_sd 159.277118043936"
> [1] "actual_sd 159.277118043936"
> Error in eval.with.vis(expr, envir, enclos) : not equal
>  > identical(expected_mean, actual_mean)
> [1] FALSE
>  > all.equal(expected_mean, actual_mean)
> [1] TRUE
>  >
> 
Your code is not reproducible, but it seems fairly clear
that you haven't yet read the help pages for identical()
and all.equal(); or, if you have, you haven't done so
very carefully. For ?identical, you'll find this:

"The function all.equal is also sometimes used to test
equality this way, but was intended for something
different: it allows for small differences in numeric
results."

For ?all.equal, you'll see mention of an argument 'tolerance'.

As a new R-user, you would be well advised to get very
familiar with the '?' key.

Welcome to R.

  -Peter Ehlers

> ______________________________________________
> 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.
> 
> 

-- 
Peter Ehlers
University of Calgary
403.202.3921




More information about the R-help mailing list