[R] problem with all/all.equal

Henrik Bengtsson hb at biostat.ucsf.edu
Thu Apr 7 06:34:05 CEST 2011


On Wed, Apr 6, 2011 at 9:23 PM, Joshua Wiley <jwiley.psych at gmail.com> wrote:
> Hi Laura,
>
> You have gotten several good suggestions.  Here are two more that may
> be helpful if you have (or potentially could have) unruly data.  In
> one case, the values are theoretically, but not computationally
> identical.  In the other, missing values lead to NA being returned,
> which may be a problem if you are using the logical test with an if()
> statement.
>
> ### Two pathologic examples ###
> # One: the floating point problem
> all((x <- c(1 - .4, .4 + .2)) == x[1])
> ifelse(length(unique(x))==1, "All Equal", "Not All Equal")
> print(x, digits = 22)
> ## another option
> tol <- .Machine$double.eps^0.5 # standard tolerance
> all(x < x[1] + tol | x > x[1] - tol)

or briefer

all(abs(x-x[1]) < tol)

or, by first doing library("R.utils"),

all(isZero(x-x[1]))


> # Two: the missing problem
> x <- c(NA, NA)
> all(x < x[1] + tol | x > x[1] - tol)

or

all(x < x[1] + tol | x > x[1] - tol, na.rm=TRUE)

or

all(isZero(x-x[1]), na.rm=TRUE)

My $.02

/Henrik

> ## another option
> isTRUE(all(x < x[1] + tol | x > x[1] - tol))
>
> Best Regards,
>
> Josh
>
> On Wed, Apr 6, 2011 at 3:09 PM, Laura Smith <smithlaura937 at gmail.com> wrote:
>> Hi!
>>
>> In a function, I may have an instance in which all elements are equal.
>>
>>> x <- rep(1,5)
>>>
>>> x
>> [1] 1 1 1 1 1
>>> identical(x)
>> Error in .Internal(identical(x, y, num.eq, single.NA, attrib.as.set)) :
>>  'y' is missing
>>> all.equal(x)
>> Error in is.expression(x) : 'x' is missing
>>>
>>
>> I don't care what particular value it is, I just want to know if they are
>> all equal.
>>
>> What am I doing wrong, please?
>>
>> Thanks,
>> Laura
>>
>>        [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> 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.
>>
>
>
>
> --
> Joshua Wiley
> Ph.D. Student, Health Psychology
> University of California, Los Angeles
> http://www.joshuawiley.com/
>
> ______________________________________________
> 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