[R] Understanding classes in R

Ista Zahn istazahn at gmail.com
Mon Sep 30 02:28:14 CEST 2013


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’."

>
>> x=1.5:100.5
>> class(x)
> [1] "numeric"
>
> Why is this class "numeric" when the class of 1:100 was integer?

Because 1.5 is not an integer. See the Value section of help(":")


>
> Thanks for your help.
>
>         [[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.



More information about the R-help mailing list