Retrieve a value from S4 class output in R -


i writing simulation in r. have decided use s4 class return 2 values in function. when run simulation, wondering how can retrieve values output calculate moments of distribution them such mean?

setclass(class="coalescent",           representation(            tmrca="numeric",            t_total="numeric"            )          ) 

the output looks below:

> tmrca_sim <-replicate(10000, coalescent_fun(n, ne)) > head(tmrca_sim) [[1]] object of class "coalescent" slot "tmrca": [1] 6.723592  slot "t_total": [1] 9.693661   [[2]] object of class "coalescent" slot "tmrca": [1] 1.592346  slot "t_total": [1] 11.50406 

what want extract values of "tmrca" , "t_total" , calculate mean. of course use many other ways simulation want learn use of classes @ same time.

you can extract data matrix:

mx <- sapply(tmrca_sim, function(x) sapply(slotnames(x), slot, object=x)) 

with made data 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 can use rowmeans or apply:

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

though note in comments, slow way of doing things in r. want coalescent_fun produce objects 2 vectors many entries each, not 1 object per simulation.


Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -