[R] Understanding classes in R

David Winsemius dwinsemius at comcast.net
Mon Sep 30 09:19:20 CEST 2013


On Sep 29, 2013, at 5:28 PM, Ista Zahn wrote:

> Hi JD,
> 
> On Sun, Sep 29, 2013 at 5:48 PM, john doe <anon.r.user at gmail.com> 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).
> 
> Yes, but the class is not the type:
> 
>> x <- 1:10
>> class(x)
> [1] "integer"
>> typeof(x)
> [1] "integer"
>> class(x) <- "foo"
>> class(x)
> [1] "foo"
>> typeof(x)
> [1] "integer"
> 
>  If so,
>> where can I see a list, and how does "numeric" fit into this system?
> 
> A list of what? For a list of storage modes see ?typof. For classes
> there cannot be any such list, as you can create a new class as easily
> as
> 
> class(x) <- "aNewClassThatNeverExistedBefore"
> 
> 
>> 
>>> 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".  How is "integer"
>> different than "numeric"?  Is there a "vector" or "array" class in R?  If
>> so, why is this not that?
> 
> See http://cran.r-project.org/doc/manuals/r-release/R-intro.html#Objects
> (And while you are there it wouldn't be a bad idea to read the rest of
> manual as well).
> 
>> 
>>> class(x[1])
>> [1] "integer"
>> 
>> This is even more confusing to me.  Because x[1] is 1.  And the class of
>> that was "numeric" in my first example.  Why is it integer now?
> 
> Presumably because '[' turned it into one. help("[") says that the
> return value is "typically an array-like R object of a similar class
> as ‘x’."

If you just type:

x <- 1 # the mode is "double" and the class is "numeric"

If you type:

x <- 1L  # mode and class are "integer"

x[1] does not coerce an "integer" to "numeric"

-- 

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list