Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make an array of classes in R?

Tags:

r

I'd like to put class objects into an array, so I can reference multiple class object. However, the class information seems to disappear when I put it into the array. How do I fix this?

like image 860
gersh Avatar asked Feb 29 '12 10:02

gersh


People also ask

Can we create array of class?

Before creating an array of objects, we must create an instance of the class by using the new keyword. We can use any of the following statements to create an array of objects. Syntax: ClassName obj[]=new ClassName[array_length]; //declare and instantiate an array of objects.

How do you declare an array class?

Syntax: Class_Name obj[ ]= new Class_Name[Array_Length]; For example, if you have a class Student, and we want to declare and instantiate an array of Student objects with two objects/object references then it will be written as: Student[ ] studentObjects = new Student[2];

How do you create an array explain with example in R?

In R, an array is created with the help of the array() function. This array() function takes a vector as an input and to create an array it uses vectors values in the dim parameter. For example- if we will create an array of dimension (2, 3, 4) then it will create 4 rectangular matrices of 2 row and 3 columns.

What is the difference between array and matrix in R?

A matrix is a two-dimensional (r × c) object (think a bunch of stacked or side-by-side vectors). An array is a three-dimensional (r × c × h) object (think a bunch of stacked r × c matrices). All elements in an array must be of the same data type (character > numeric > logical).


1 Answers

Arrays aren't the right tool for this, as they are atomic (so allow only one basic type of data) and also allow only numeric or character data. A list is a generic vector in R and as such each component of a list can contain any type of object.

Here is an example for two user defined S3 classes:

> foo <- 1:10
> class(foo) <- "foo"
> bar <- "a"
> class(bar) <- "bar"
> 
> obj <- list(foo = foo, bar = bar)
> obj
$foo
 [1]  1  2  3  4  5  6  7  8  9 10
attr(,"class")
[1] "foo"

$bar
[1] "a"
attr(,"class")
[1] "bar"
like image 146
Gavin Simpson Avatar answered Sep 21 '22 19:09

Gavin Simpson