library("label.switching")

load("C:/Users/Chris/Desktop/LCA/example.RData")

N <- 400      # sample size
m <- 3        # number of components
nMCMC <- 3327 # number of MCMC iterations after burnin and thinning

# Relabeling across MCMCs
# z.MCMC: a nMCMC_by_N matrix containing labels for subjects
# w.MCMC: a nMCMC_by_m matrix containing mixing weights
run <- ecr.iterative.1(z = z.MCMC, K = 3)
neworder <- run$permutations
w.reorder <- matrix(0, nrow=nMCMC, ncol=3)
for(i in 1:nMCMC) {
  w.reorder[i,] <- w.MCMC[i,][neworder[i,]]
}

# Trace plots before and after relabeling
x11()
par(mfrow=c(1,2))
matplot(w.MCMC, type="l", col=c("black","red","blue"), ylim=c(0.1,0.7),
        ylab = "Weights", xlab = "Retained iterations",
        main="Trace plot of weights before relabeling",
        cex.lab=1, cex.axis=1, cex.main=1)
legend("topright", legend=c("Class 1", "Class 2", "Class 3"),
       col=c("black","red","blue"), lty=1, lwd=2, cex=1)
matplot(w.reorder, type="l", col=c("black","red","blue"), ylim=c(0.1,0.7),
        ylab = "Weights", xlab = "Retained iterations",
        main="Trace plot of weights after relabeling",
        cex.lab=1, cex.axis=1, cex.main=1)
legend("topright", legend=c("Class 1", "Class 2", "Class 3"),
       col=c("black","red","blue"), lty=1, lwd=2, cex=1)
