Reputation: 2437
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?
Upvotes: 5
Views: 7188
Reputation: 47642
I think you are misinterpreting the concept "array" in R. An array in R is not a vector of different objects but a multidimensional object with only elements of one class. A list
is the R object that can be used to store whatever you want. If you want, you can even give it dimensions so you can get a multi-dimensional list, which would correspond to the array you describe. This must be indexed with double square brackets.
Example:
# A list with different objects:
foo <- list("A","B","C","D",1,2,3,4,TRUE,TRUE,FALSE,FALSE)
# Add dimensions:
dim(foo) <- c(2,2,3)
> foo
, , 1
[,1] [,2]
[1,] "A" "C"
[2,] "B" "D"
, , 2
[,1] [,2]
[1,] 1 3
[2,] 2 4
, , 3
[,1] [,2]
[1,] TRUE FALSE
[2,] TRUE FALSE
# index row 1 col 1 slice 1
> foo[[1,1,1]]
[1] "A"
Upvotes: 5
Reputation: 174948
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"
Upvotes: 7