So I have this function which mxRuns an mxModel, and returns the fitted mxModel object very nicely. I can access the slots of this object just fine. However, I'd like to call this function a number of times in a loop (or using apply variant). I do not seem to be able to build a list of mxModel objects from which I can extract elements.
firstrun <- runACEModelContinuous(TwinPairDTIDemog,varname='FLFAminus58',t1suffix='Twin1',t2suffix='Twin2',idzyg='ZYGOSITYTwin1',extractionMZ=.(ZYGOSITYTwin1=='M'),extractionDZ=.(ZYGOSITYTwin1=='D'))
that works fine, and I can see, e.g.,
firstrun$ACE.A
> firstrun$ACE.A
mxAlgebra 'A'
@formula: X %*% t(X)
@result:
[,1]
[1,] 1.930580e-13
dimnames: NULL
However, if I populate a list with the mxModel objects returned by this function in a loop, the list elements lose their nice mxModel object accessibility:
i<-0
for (variable in names(TwinDTI)[2:4]){
i<-i+1
results <- c(results,runACEModelContinuous(TwinPairDTIDemog,varname=variable,t1suffix='Twin1',t2suffix='Twin2',idzyg='ZYGOSITYTwin1',extractionMZ=.(ZYGOSITYTwin1=='M'),extractionDZ=.(ZYGOSITYTwin1=='D')))
}
temp<-results[3]
temp is visible as a list object but nothing "inside" it can be pulled out:
> temp$ACE.A
NULL
Any suggestions on how to make a vector or list of mxModel objects that don't lose their nice slotty attributes?
Hi Mike,
Two suggestions. First, use a lapply() to execute several models instead of a loop. Then it will be easier to parallelize by replacing the lapply() with omxLapply(). To use lapply(), it is easiest to write a helper function:
Then use the helper function in a call to lapply:
The second suggestion is to use the [[ operator when you are extracting a single entity from a list. I'm not sure if 'results' is a list or a vector in your version of the code. It should be a list, but c() may be trying to coerce the elements into a vector, which would be bad. In any case, when operating on a list, the [[ operator and [ operator have slightly different behaviors. So use [[ when you are certain you want to extract a single element.