Search code examples
rr-s4

Retrieve a value from S4 class output in R


I am writing a simulation in R. I have decided to use S4 class to return two values in my function. When I run the simulation, I am wondering how I can retrieve the values from the output to calculate moments of distribution from them such as mean?

setClass(Class="Coalescent", 
         representation(
           TMRCA="numeric",
           t_total="numeric"
           )
         )

The output looks like below:

> TMRCA_sim <-replicate(10000, Coalescent_fun(n, Ne))
> head(TMRCA_sim)
[[1]]
An object of class "Coalescent"
Slot "TMRCA":
[1] 6.723592

Slot "t_total":
[1] 9.693661


[[2]]
An object of class "Coalescent"
Slot "TMRCA":
[1] 1.592346

Slot "t_total":
[1] 11.50406

What I would want to do is to extract all the values of "TMRCA" and "t_total" and calculate the mean. Of course I could use many other ways to do the simulation but I want to learn the use of classes at the same time.


Solution

  • You can extract your data into a matrix:

    mx <- sapply(TMRCA_sim, function(x) sapply(slotNames(x), slot, object=x))
    

    With some made up data this is what mx looks like:

                 [,1]      [,2]      [,3]      [,4]      [,5] 
    TMRCA   0.3823880 0.3403490 0.5995658 0.1862176 0.6684667 
    t_total 0.8696908 0.4820801 0.4935413 0.8273733 0.7942399 
    

    And then you can use rowMeans or apply:

    rowMeans(mx)
    apply(mx, 1, mean)  # equivalent, though slower and more flexible
    apply(mx, 1, var)
    

    Though as I note in my comments, this is a really slow way of doing things in R. You want your Coalescent_fun to produce objects with two vectors with many entries each, not one object per simulation.