[R] identical(length(x), 1) returns FALSE, but print(length(x)) is 1, length(x)==1 is TRUE, and is.integer(lenght(x)) is TRUE????

Gavin Simpson gavin.simpson at ucl.ac.uk
Tue Sep 15 19:24:03 CEST 2009


On Tue, 2009-09-15 at 18:04 +0100, Corrado wrote:
> On Tuesday 15 September 2009 17:28:02 Gavin Simpson wrote:
> > [note you don't give us your x so I'm making this up - This is what
> > Duncan was going on about in an earlier thread, give us something we can
> > just paste into R and it works]
> 
> Dear Gavin,
> 
> I do not understand what more information! Take any vector of length 1, for 
> example x<-1. Plus all the command that where in my previous email ....

So why don't you put

at the start of you code so all we have to do is paste it in?

I grabbed the code pasted it in without thinking and it failed, only
then did I really look at it. At that stage you might loose people who
are busy. Unfortunately for you (and others) those people tend to be one
the ones that know R the best and give the most insightful answers.

> 
> What is the logic behind  
> 
> identical(length(x),1)
> 
> being false?

I and the other responders showed you that in R, 1 is a double and thus
is different to the object returned from length(x), which is an integer.

identical tests for exact equality of /objects/. An integer is not a
double. Are you confusing the object with the contents of said object?
Even then they are different for the reason mentioned

> typeof(1)
[1] "double"
> typeof(1L)
[1] "integer"
> typeof(length(1))
[1] "integer"

identical is comparing the objects. 1 is and orange, length(x) returns
an apple. They are different despite the fact that the innards are both
nice, sweet and juicy. This is what identical is telling you.

If you want to know whether length(1) (i.e. 1) is equal to 1 then you
can use == or make your comparison in identical exact and cast 1 and an
integer using 1L.

My bit of rubbish I posted may not be so rubbish here if your real use
case involves any computations, for example in a situation where

isTRUE(all.equal(length(x), Y))

where Y is the result of some other computation.

HTH

G

> 
> Regards
-- 
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
 Dr. Gavin Simpson             [t] +44 (0)20 7679 0522
 ECRC, UCL Geography,          [f] +44 (0)20 7679 0565
 Pearson Building,             [e] gavin.simpsonATNOSPAMucl.ac.uk
 Gower Street, London          [w] http://www.ucl.ac.uk/~ucfagls/
 UK. WC1E 6BT.                 [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%




More information about the R-help mailing list