[R] Integer vs numeric

Peter Dalgaard p.dalgaard at biostat.ku.dk
Mon Jan 28 23:40:02 CET 2008

(Ted Harding) wrote:
> Further to the above: The help
>   ?":"
> says:
> Value:
>   For numeric arguments [as opposed to factors],
>   a numeric vector. This will be of type 'integer'
>   if 'from' and 'to' are both integers and
>   representable in the integer type, otherwise of
>   type 'numeric'.
> By "if 'from' and 'to' are both integers" I understand
> it to mean "if the values of 'from' and 'to' are
> integers (in the mathematical realm)", i.e. this
> does not refer to the R type.
In the realm of floating point arithmetic to be precise. Fractional part 
zero is one way of putting it. "Representable in integer type" refers to 
the fact that double precision has 53 bits for the mantissa and integers 
have 32, so some floating point integers won't fit. The point is of 
course that 1.3:9.3 is _not_ an integer vector.

> Thus:
>   a<-1; b<-2
>   str(a)
>   # num 1
>   str(b)
>   # num 2
>   str((a:b))
>   # int [1:2] 1 2
> so a and b were numeric when created, but since their
> values are integers (etc.) (a:b) has integer type.
> Presumably this is for computational efficiency.
> Integer arithmetic on a computer is faster than
> floating-point arithmetic; and if the computation
> can be done in the CPU registers ("register arithmetic")
> then it is faster still (as I presume is the case here).
AFAIR, space is/was more of an issue. If you do something like

for i in 1:1e7

then you have 40 MB sitting there doing nothing, and 80 MB if it had 
been floating point.

Also AFAIR, the reason 1 is not integer is that then every operation 
like x-1 would involve a coercion to double.
> Mind you. I'm guessing here. I have had nothing to do
> with the implementation of arithmetic in R, so cannot
> answer authoritatively for the motivations of those
> who did!

   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907

More information about the R-help mailing list