Search code examples
rr-s4

How to create an S4 class A that will have a list of S4 classes B as its attribute?


I am quite new to R so my question might have an obvious answer.

I am trying to create something like this

A {
  list: B []
}

Where both A and B are S4 classes. How to achieve that?

EDIT

I actually do not care at this point whether list attribute is an array or an actual list. For my use case it is fairly irrelevant.


Solution

  • You define S4 classes with setClass, and within this you use representation to declare members and their types.

    In this case, class A needs only contain a member of type list to house the collection of objects of S4 class B.

    setClass("A", representation(List = "list"))
    setClass("B", representation(value = "numeric"))
    

    You declare new S4 objects with the function new, in which you specify the class name first and their members as named parameters:

    my_object <- new("A", List = list(new("B", value = 1), new("B", value = 2)))
    my_object
    #> An object of class "A"
    #> Slot "List":
    #> [[1]]
    #> An object of class "B"
    #> Slot "value":
    #> [1] 1
    #> 
    #> 
    #> [[2]]
    #> An object of class "B"
    #> Slot "value":
    #> [1] 2
    

    We can get the List member using the @ operator:

    my_object@List
    #> [[1]]
    #> An object of class "B"
    #> Slot "value":
    #> [1] 1
    #> 
    #> 
    #> [[2]]
    #> An object of class "B"
    #> Slot "value":
    #> [1] 2
    

    From which we can access the list members, and their S4 slots directly:

    my_object@List[[1]]
    #> An object of class "B"
    #> Slot "value":
    #> [1] 1
    
    my_object@List[[1]]@value
    #> [1] 1
    

    Created on 2020-03-16 by the reprex package (v0.3.0)