0

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.

Bruce
  • 79
  • 7
  • don't you just need `max(mlmat[,1])` ? If this is not the answer you are looking for, you need to add more information. – Edo May 08 '23 at 08:21
  • @Edo I need objects that belong to gss.lc with a maximum of log-likelihood. When I run the loop, although it will save the message of mlmat[i,1], there will only be one gss.lc, and this gss.lc seems It is the object when i=1, he is not the maximum of log-likelihood. Thank you. – Bruce May 08 '23 at 10:48

1 Answers1

1

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
Edo
  • 7,567
  • 2
  • 9
  • 19
  • I also used `list` later, but I will use `mlmat` table to check one by one to find the most value and select it. Your method saves a lot of time, thank you. But I want to verify and see if there is a way to pick out its `llik` directly from the 500 objects in `gss.lcs`and make it like my `mlmat`? – Bruce May 09 '23 at 02:17
  • with map you can extract whatever you want from a list. Specifically gss.lcs |> map_dbl("llik") will extract a vector of llik exactly like in mlmat. – Edo May 09 '23 at 13:45