rloopsmaxlog-likelihood

How to save global of maximum log-likelihood data from loop?


I am doing this:

## Example data
library(poLCA)
data(gss82)
f <- cbind(PURPOSE,ACCURACY,UNDERSTA,COOPERAT)~1

mlmat <- matrix(NA,nrow=500,ncol=4)

## Do repreat 500 times LCA for best llik
for (i in 1:500) {
  gss.lc <- poLCA(f,gss82,nclass=3,maxiter=3000,tol=1e-7)
  mlmat[i,1] <- gss.lc$llik
  o <- order(gss.lc$probs$UNDERSTA[,1],decreasing=T)
  mlmat[i,-1] <- gss.lc$P[o]
 }

It's come from poLCA paper (http://www.sscnet.ucla.edu/polisci/faculty/lewis/pdf/poLCA-JSS-final.pdf p14. table1)

This is result: enter image description here

I use loop to do 500 times just show one objective on data panel of R.

I want know how to just save the maximumlog-likelihood is -2754.545 output, because it's global of maximum log-likelihood.


Solution

  • Based on the comment you left, you don't need a for loop and you don't need mlmat.

    You can run 500 times the same code and save the results into a list. Then you select the item of the list with the highest llik. At that point you can just select the item of the list that you are looking for.

    library(purrr)
    
    # run 500 times
    gss.lcs <- map(1:500, \(i) poLCA(f,gss82,nclass=3,maxiter=3000,tol=1e-7))
    
    # get the position of the highest one
    pos <- gss.lcs |> map_dbl("llik") |> which.max()
    pos
    
    # get the element with the highest llik
    gss.lc <- gss.lcs[[pos]]
    
    gss.lc