[R] Understanding classes in R

David Winsemius dwinsemius at comcast.net
Mon Sep 30 01:39:33 CEST 2013


On Sep 29, 2013, at 2:48 PM, john doe wrote:

> I am having trouble understanding how classes in R work.  Here is a small
> reproducable example:
> 
>> x=1
>> class(x)
> [1] "numeric"
> 
> OK.  When a variable is a number, its class is "numeric".  Does R have
> multiple types for numbers, like C++ (eg integer, float, double).  If so,
> where can I see a list, and how does "numeric" fit into this system?
> 
>> x=1:100
>> class(x)
> [1] "integer"
> 
> Wait - I thought that I assigned x to be an array/vector of 100 integers
> (numerics).  Why is the class not "array" or "vector".

Well, it is a vector. But it's not an array because it has no 'dim' attribute. The ":" operator returns integer sequences.

?":"

>  How is "integer"
> different than "numeric"?  Is there a "vector" or "array" class in R?

Yes.

?array
?vector
?is.vector

>  If
> so, why is this not that?
> 
>> class(x[1])
> [1] "integer"
> 
> This is even more confusing to me.  Because x[1] is 1.

Look at:

x=1L
class(x)

>  And the class of
> that was "numeric" in my first example.  Why is it integer now?
> 
>> x=1.5:100.5
>> class(x)
> [1] "numeric"
> 
> Why is this class "numeric" when the class of 1:100 was integer?
> 

Intergers are stored as 4-byte per item with a bit of overhead, which numerics or doubles are stored with 8 bytes:

>  object.size(1:100000)
400040 bytes
> object.size( (1:100000)+.5 )
800040 bytes

As you can see it is very easy to corce an integer to numeric.

> Thanks for your help.
> 
> 	[[alternative HTML version deleted]]

And do learn to post in plain text.

> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.


-- 
David Winsemius
Alameda, CA, USA



More information about the R-help mailing list