Paso 2.8

Análisis de clases latentes exploratoria y comparativa con predictores, aunque con datos imputados (salvo en “pertenece a pueblo originario”)

Andrés González Santa Cruz
May 06, 2023
Show code
script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"
Show code
 $(document).ready(function() {
    $('body').prepend('<div class=\"zoomDiv\"><img src=\"\" class=\"zoomImg\"></div>');
    // onClick function for all plots (img's)
    $('img:not(.zoomImg)').click(function() {
      $('.zoomImg').attr('src', $(this).attr('src')).css({width: '100%'});
      $('.zoomDiv').css({opacity: '1', width: 'auto', border: '1px solid white', borderRadius: '5px', position: 'fixed', top: '50%', left: '50%', marginRight: '-50%', transform: 'translate(-50%, -50%)', boxShadow: '0px 0px 50px #888888', zIndex: '50', overflow: 'auto', maxHeight: '100%'});
    });
    // onClick function for zoomImg
    $('img.zoomImg').click(function() {
      $('.zoomDiv').css({opacity: '0', width: '0%'}); 
    });
  });
  
Show code
<script src="hideOutput.js"></script> 
Show code
$(document).ready(function() {    
    $chunks = $('.fold');    
    $chunks.each(function () {      // add button to source code chunks     
    if ( $(this).hasClass('s') ) {       
        $('pre.r', this).prepend("<div class=\"showopt\">Show Source</div><br style=\"line-height:22px;\"/>");
            $('pre.r', this).children('code').attr('class', 'folded');     
            }      // add button to output chunks     
        if ( $(this).hasClass('o') ) {       
            $('pre:not(.r)', this).has('code').prepend("<div class=\"showopt\">Show Output</div><br style=\"line-height:22px;\"/>");       
            $('pre:not(.r)', this).children('code:not(r)').addClass('folded');        // add button to plots       
            $(this).find('img').wrap('<pre class=\"plot\"></pre>');       
            $('pre.plot', this).prepend("<div class=\"showopt\">Show Plot</div><br style=\"line-height:22px;\"/>");       
            $('pre.plot', this).children('img').addClass('folded');      
            }   
});    // hide all chunks when document is loaded   
    $('.folded').css('display', 'none')    // function to toggle the visibility   
    $('.showopt').click(function() {     
            var label = $(this).html();     
            if (label.indexOf("Show") >= 0) {       
                $(this).html(label.replace("Show", "Hide"));     
            } else {
              $(this).html(label.replace("Hide", "Show"));     
            }     
    $(this).siblings('code, img').slideToggle('fast', 'swing');   
    }); 
}); 

Cargamos los datos

Show code
rm(list = ls());gc()
         used (Mb) gc trigger (Mb) max used (Mb)
Ncells 535756 28.7    1208875 64.6   643711 34.4
Vcells 907377  7.0    8388608 64.0  1649632 12.6
Show code
[1] "2023-05-06 08:53:17 -04"
Show code
load("data2_lca2_imp_2023_05_06.RData")

Cargamos los paquetes

Show code
knitr::opts_chunk$set(echo = TRUE)

if(!require(poLCA)){install.packages("poLCA")}
if(!require(poLCAParallel)){devtools::install_github("QMUL/poLCAParallel@package")}
if(!require(compareGroups)){install.packages("compareGroups")}
if(!require(parallel)){install.packages("parallel")}
if(!require(Hmisc)){install.packages("Hmisc")}
if(!require(tidyverse)){install.packages("tidyverse")}
try(if(!require(sjPlot)){install.packages("sjPlot")})
if(!require(emmeans)){install.packages("emmeans")}
if(!require(nnet)){install.packages("nnet")}
if(!require(here)){install.packages("here")}
if(!require(doParallel)){install.packages("doParallel")}
if(!require(progress)){install.packages("progress")}
if(!require(caret)){install.packages("caret")}
if(!require(rpart)){install.packages("rpart")}
if(!require(rpart.plot)){install.packages("rpart.plot")}
if(!require(partykit)){install.packages("partykit")}
if(!require(randomForest)){install.packages("randomForest")}
if(!require(ggcorrplot)){install.packages("ggcorrplot")}
if(!require(polycor)){install.packages("polycor")}
if(!require(tableone)){install.packages("tableone")}
if(!require(broom)){install.packages("broom")}
if(!require(plotly)){install.packages("plotly")}
if(!require(rsvg)){install.packages("rsvg")}
if(!require(DiagrammeRsvg)){install.packages("DiagrammeRsvg")}

#if(!require(poLCA)){githubinstall::gh_install_packages("poLCA", ref = github_pull("14"))}

#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:
#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:
#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:#:

Definimos ciertas constantes

Show code
clus_iter= 500 #500
n_thread <- parallel::detectCores()
nrep <- clus_iter # number of different initial values (could be n_thread too)
n_class_max <- 10 # maximum number of classes to investigate
n_bootstrap <- 100 #30 # 50 number of bootstrap samples
print(n_thread)
[1] 8

Análisis de clases latentes

Modelo alternativo

Análisis ACL alt

Show code
#Biemer, P. P., & Wiesen, C. (2002). Measurement error evaluation of self-reported drug use: a latent class analysis of the US National Household Survey on Drug Abuse. Journal of the Royal Statistical Society: Series A (Statistics in Society), 165(1), 97–119. doi:10.1111/1467-985x.00612  
#lca_entropia(x="ppio", seed= 2125, k= 8, f= f_preds, dat= mydata_preds, nbr_repet= 30, na_rm= T)
#3
#<div style="border: 1px solid #ddd; padding: 5px; overflow-y: scroll; height:400px; overflow-x: scroll; width:100%">
# f is the selected variables
# dat is the data
# nb_var is the number of selected variables
# k is the number of latent class generated
# nbr_repet is the number of repetition to  
# reach the convergence of EM algorithm
# x es el código para las variables de los modelos
#seed es el numero random para las semillas. ej: 4345.
#Modo de calcular el mejor modelo.
#z_ # 
#2023-01-20
#https://github.com/QMUL/poLCAParallel/blob/master/exec/3_blrt.R
#0h s
f_adj<-cbind(CAUSAL, EDAD_MUJER_REC, PUEBLO_ORIGINARIO_REC, PAIS_ORIGEN_REC, HITO1_EDAD_GEST_SEM_REC, MACROZONA, PREV_TRAMO_REC)~ outcome

seed<-2125
old <- Sys.time()

require(progress)

set.seed(seed)
model_array_adj <- list()  # Initialize an empty list to store the results
pb <- progress_bar$new(total = n_class_max, message_class = "Running poLCA")

#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_
for (k in 1:n_class_max) {
  nrep_int <- nrep  # Initialize nrep to a reasonable value
  while (nrep_int >= 1) {  # Try running poLCA with decreasing nrep until nrep reaches 1
    tryCatch({
      set.seed(seed)
      mod <- poLCAParallel::poLCA(
        f_adj, 
        mydata_preds3 %>% dplyr::mutate(outcome=ifelse(outcome==1,1,0)), # %>% janitor::tabyl(outcome)
        nclass = k, 
        nrep = nrep_int, 
        maxiter = 1e4,
        n.thread = 12,
        verbose = FALSE
      )
      model_array_adj[[k]] <- mod  # Store the result if no error occurs
      break  # Exit the loop if poLCA succeeds
    }, error = function(e) {
      message(paste("Error in poLCA for k =", k, ", nrep =", nrep_int, ":", conditionMessage(e)))
      nrep_int <- nrep_int / 2  # Reduce nrep by half if poLCA fails
    })
  }
#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_  
  pb$tick()  # Increment the progress bar
  cat(sprintf("\r%d%% completed", round(k/n_class_max*100)))  # Print progress percentage
  Sys.sleep(.05)
}

 ALERT: covariates not allowed when nclass=1;
                 will be ignored. 
 

10% completed
20% completed
30% completed
40% completed
50% completed
60% completed
70% completed
80% completed
90% completed
100% completed
Show code
pb$terminate()  # Close the progress bar
cat(': Done')  # Print "Done" message  
: Done
Show code
model_array_adj_ppio<-model_array_adj

#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_
#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#BOOTSTRAP#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_
#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_

new_med<-(Sys.time())
paste0("The model took ",round(new_med-old,2)," until every LCA was computed")
[1] "The model took 6.18 until every LCA was computed"

Luego calculamos la razón de verosimilitud mediante remuestreo bootstrap (BLRT) entre los distintos modelos con el que asume una clase menos.

Show code
# store p values for each nclass, 1 to n_class_max
# store 0 for 1 number of class, ie this says you cannot have zero number of
# classes
p_value_array_adj <- c(0)
# for all number of classes investigated:
#   - store the log likelihood ratio
#   - store all bootstrap samples log likelihoods ratios
fitted_log_ratio_array_adj <- rep(NaN, n_class_max)
bootstrap_log_ratio_array_adj <- list()

#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_
# do the bootstrap likelihood ratio test for each number of classes
for (nclass in 2:n_class_max) {

  # get the null and alt models
  # these are models with one number of class differences
  null_model_adj <- model_array_adj_ppio[[nclass - 1]]
  alt_model_adj <- model_array_adj_ppio[[nclass]]

  # for each bootstrap sample, store the log likelihood ratio here
  bootstrap_results_adj <- poLCAParallel::blrt(
    null_model_adj, alt_model_adj,
    n_bootstrap, n_thread, nrep
  )

  # log likelihood ratio to compare the two models
  fitted_log_ratio_array_adj[nclass] <- bootstrap_results_adj[["fitted_log_ratio"]]
  # store the log likelihoods ratios for all bootstrap samples
  bootstrap_log_ratio_array_adj[[nclass]] <-
    bootstrap_results_adj[["bootstrap_log_ratio"]]
  # store the p value for this nclass
  p_value_array_adj <- c(p_value_array_adj, bootstrap_results_adj[["p_value"]])
  
  #progress bar
  cat(paste0(round(nclass / n_class_max * 100), '% completed'))
  Sys.sleep(.05)
  if (nclass == n_class_max) cat(': Done')
  else cat('\014')
}
20% completed30% completed40% completed50% completed60% completed70% completed80% completed90% completed100% completed: Done
Show code
#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_
new<-(Sys.time())
time_diff <- (Sys.time() - old)/60
paste0("The model took ",round(new-old,2)," minutes")
[1] "The model took 14.29 minutes"
Show code
model_array_ppio2 <- model_array_adj
fitted_log_ratio_array_adj_ppio <- fitted_log_ratio_array_adj
bootstrap_log_ratio_array_adj_ppio <- bootstrap_log_ratio_array_adj
bootstrap_results_adj_ppio <- bootstrap_results_adj
p_value_array_adj_ppio <- p_value_array_adj

# Get the BIC values for all models in model_array_ppio2
bic_values_adj <- sapply(model_array_ppio2, function(model) model$bic)

# Identify the index of the model with the lowest BIC
best_model_index_adj <- which.min(bic_values_adj)

# Select the best model
LCA_best_model_adj_ppio <- model_array_ppio2[[best_model_index_adj]]
#####################################################################################################################################################################
#Within poLCA, parameter estimates are obtained by a procedure that repeatedly improves estimates.
#This is stopped when no further improvements are obtained, or until a maximum number of iterations is reached. The starting values are the values at which such repetitions were started. Increasing the number 4 R. ACHTERHOF ET AL.of iterations (cycles within each estimation) and setting more different starting values for each repetition results in a greater likelihood that the global (rather than local) maximum of the log-likelihood function (and thus, the best possible solution) is reached. The maximum number of iterations was chosen as 10.000, and 500 different sets of starting values were used (thus going beyond the recommendations by Linzer & Lewis, 2011; Oberski, 2016). As such, the influence of chance was minimized while the reproducibility of the results was maximized# 

Resultados ACL alt

Hicimos un gráfico de los resultados

Show code
# Initialize an empty data frame
tab_ppio2 <- data.frame()##

# Loop through each model
for (i in 2:n_class_max) {
  skip_to_next <- FALSE

  # Get the model and the previous model
  mod2 <- model_array_ppio2[[i]]
  mod2_min1 <- model_array_ppio2[[(i-1)]]

  # Check if the model has valid predictions
  if (is.null(mod2$predclass)) {
    skip_to_next <- TRUE
  }

  # If the model has valid predictions, calculate the measures and add them to the data frame
  if (!skip_to_next) {
    # Number of latent classes
    mod2$C <- max(t(matrix(apply(mod2$y, 2, max))))
    # Number of manifest variables
    mod2$J <- ncol(mod2$y)
    # Total number of items
    mod2$I <- mod2$J * mod2$C
    # Degrees of freedom
    mod2$df <- mod2$C^mod2$I - mod2$npar - 1
    # Chi-square test
    mod2$Chisq.pvalue <- (1 - pchisq(mod2$Chisq, mod2$df))
    # AIC
    mod2$aic <- round(mod2$aic, 2)
    # BIC
    mod2$bic <- round(mod2$bic, 2)
    # Adjusted BIC n*=(n+2)/24 (https://github.com/dlinzer/poLCA/issues/10)
    mod2$aBIC <- round((-2 * mod2$llik) + (log((mod2$N+2)/24) * mod2$npar), 2) 
    # Conditional AIC
    mod2$cAIC <-  round((-2 * mod2$llik) + (2 * mod2$Nobs * log(mod2$N/mod2$Nobs)), 2)
    # approximate weight of evidence criterion  #https://jbds.isdsa.org/public/journals/1/html/v2n2/qiu/
    mod2$awe <-  round((-2 * mod2$llik) + (2 * mod2$npar * log(mod2$Nobs)+1.5), 2)    
    # Gsq: deviance
    mod2$Gsq
    # Likelihood ratio test
    mod2$Gsq.pvalue <- (1 - pchisq(mod2$Gsq, mod2$df))
    # Relative entropy
    mod2$RelEnt <- round(relative.entropy(mod2), 2)
    # Entropy R-squared
    mod2$EntR2 <- round(entropy.R2(mod2), 2)
    # Deviance change
    mod2$DevChange <- round(mod2_min1$Gsq - mod2$Gsq, 2)
    # Degrees of freedom change
    mod2$dfChange <- mod2_min1$resid.df - mod2$resid.df
    # P-value for deviance change
    mod2$pvalDevChange <- round(pchisq(mod2$DevChange, mod2$dfChange, lower.tail = FALSE), 4)
    mod2$BLRT <- round(fitted_log_ratio_array_adj_ppio[[i]],2)
    mod2$BLRT.pvalue <- p_value_array_adj_ppio[[i]]
    # Add the model index to the data frame
    mod2$ModelIndex <- i

    tab_ppio2 <- rbind.data.frame(tab_ppio2, t(data.matrix(mod2[c("llik", "Chisq", "Chisq.pvalue", "resid.df", "aic", "bic", "aBIC", "cAIC", "awe", "Gsq", "Gsq.pvalue", "RelEnt", "EntR2", "DevChange", "dfChange", "pvalDevChange", "ModelIndex","BLRT", "BLRT.pvalue")])))

    #  } else {}
  }
}

# identify the list-like columns
list_cols2 <- sapply(tab_ppio2, is.list)
# unlist the list-like columns
unlisted_cols2 <- lapply(tab_ppio2[list_cols2], unlist)
# bind the unlisted columns as a data frame
tab_ppio2 <- cbind(tab_ppio2[!list_cols2], do.call(cbind, unlisted_cols2))
#Erase rownames
rownames(tab_ppio2) <- NULL

manualcolors2 <- c('indianred1', 'cornflowerblue', 'gray50', 'darkolivegreen4', 'slateblue2', 
                  'firebrick4', 'goldenrod4')
levels2 <- c("llik", "Chisq", "Chisq.pvalue", "resid.df", "aic", "bic", "aBIC", "cAIC", "awe",
            "Gsq", "Gsq.pvalue", "RelEnt", "EntR2", "DevChange", "dfChange",
            "pvalDevChange", "BLRT", "BLRT.pvalue")
labels2 <- c('Log-Verosimilitud', 'Chi2', 'valor p Chi2', 'Grados de libertad', 
            'Criterio de Información\nde Akaike(AIC)'','Criterio de Información\nBayesiano (BIC)')''BIC Ajustado (SABIC)')'"AIC Corregido"o'Peso de evidencia aproximado(awe)')'G-squared/Deviance'e''Valor p G-squared'd''Entropía Relativa'va'Entropía R2' R'Cambio en Deviance\n(con modelo previo)'io'Grados de libertad del cambio'bi'valor p cambio deviance'nc'BLRT'LR'valor p BLRT')RT')
fig_lca_fit2<- tab_ppio2 %>%
  dplyr::mutate_if(is.character, as.numeric) %>%  # convert character columns to numeric
  tidyr::pivot_longer(cols = -ModelIndex, #"evryone but index"
                       names_to = "indices", values_to = "value", values_drop_na = F) %>%
  dplyr::mutate(indices = factor(indices, levels = levels2, labels = labels2)) %>%
  dplyr::filter(grepl("(AIC|BIC|awe)",indices, ignore.case=T))%>%
  dplyr::mutate(ModelIndex= factor(ModelIndex, levels=2:n_class_max)) %>% 
  ggplot(aes(x = ModelIndex, y = value, group = indices, color = indices, linetype = indices)) +
  geom_line(size = 1.5) +
  scale_color_manual(values = manualcolors) +
  #scale_linetype_manual(values = c("solid", "dashed", "dotted")) +
  labs(x = "Número de clases"", y=="Valor"", color=="Medida"", linetype=="Medida"))++
  #facet_wrap(.~indices, scales = "free_y", nrow = 4, ncol = 1) +
  theme_bw()

fig_lca_fit2
Show code
ggsave("_fig2_comparison_adj_imp.png",fig_lca_fit2, dpi=600)

Luego en una tabla

Show code
tab_ppio2 %>%#
  dplyr::select(ModelIndex, everything()) %>% 
    dplyr::mutate_if(is.character, as.numeric) %>%  # convert character columns to numeric
    knitr::kable(format="markdown", caption="Fit measures of models")
Table 1: Fit measures of models
ModelIndex llik Chisq Chisq.pvalue resid.df aic bic aBIC cAIC awe Gsq Gsq.pvalue RelEnt EntR2 DevChange dfChange pvalDevChange BLRT BLRT.pvalue
2 -27132.08 11595.052 1 3735 54372.15 54709.11 54537.52 54264.15 55155.56 4753.085 1 0.94 0.93 2837.46 28 0 2884.37 0
3 -26844.96 9256.635 1 3707 53853.92 54365.59 54105.03 53689.92 55042.76 4246.279 1 0.80 0.77 506.81 28 0 574.23 0
4 -26674.22 9473.370 1 3679 53568.44 54254.83 53905.30 53348.44 55162.71 3946.200 1 0.75 0.73 300.08 28 0 341.48 0
5 -26532.59 8561.743 1 3651 53341.19 54202.29 53763.79 53065.19 55340.89 3646.079 1 0.78 0.76 300.12 28 0 283.25 0
6 -26431.42 8457.283 1 3623 53194.84 54230.65 53703.18 52862.84 55599.97 3559.346 1 0.75 0.73 86.73 28 0 202.35 0
7 -26354.63 9186.551 1 3595 53097.26 54307.80 53691.36 52709.26 55907.83 3398.872 1 0.83 0.80 160.47 28 0 153.57 0
8 -26559.78 8141.894 1 3567 53563.56 54948.81 54243.40 53119.56 56779.56 3672.379 1 0.89 0.88 -273.51 28 1 -410.30 1
9 -26783.30 8942.604 1 3539 54066.60 55626.56 54832.18 53566.60 57688.02 4073.041 1 0.91 0.86 -400.66 28 1 -447.03 1
10 -26679.26 8587.431 1 3511 53914.52 55649.20 54765.84 53358.52 57941.38 3927.284 1 0.88 0.78 145.76 28 0 208.08 0

Presentamos el modelo con mejor ajuste

Show code
print(LCA_best_model_adj_ppio) #
Conditional item response (column) probabilities,
 by outcome variable, for each class (row) 
 
$CAUSAL
          Pr(1)  Pr(2)  Pr(3)  Pr(4)
class 1:      0 0.2744 0.7256 0.0000
class 2:      0 0.0084 0.0000 0.9916
class 3:      0 0.0803 0.9197 0.0000
class 4:      0 0.4250 0.5750 0.0000
class 5:      0 0.9798 0.0202 0.0000

$EDAD_MUJER_REC
          Pr(1)  Pr(2)  Pr(3)  Pr(4)  Pr(5)  Pr(6)
class 1:      0 0.0447 0.3088 0.3244 0.2613 0.0607
class 2:      0 0.3289 0.3128 0.2186 0.1180 0.0218
class 3:      0 0.0000 0.1087 0.3114 0.5061 0.0739
class 4:      0 0.0167 0.3010 0.3270 0.3012 0.0541
class 5:      0 0.0084 0.2213 0.4345 0.3010 0.0349

$PUEBLO_ORIGINARIO_REC
           Pr(1)  Pr(2)  Pr(3)
class 1:  0.2179 0.7232 0.0589
class 2:  0.1480 0.8092 0.0428
class 3:  0.1340 0.8660 0.0000
class 4:  0.1547 0.8099 0.0354
class 5:  0.1094 0.8444 0.0462

$PAIS_ORIGEN_REC
          Pr(1)  Pr(2)  Pr(3)
class 1:      0 0.9729 0.0271
class 2:      0 0.7796 0.2204
class 3:      0 0.9213 0.0787
class 4:      0 0.0215 0.9785
class 5:      0 0.8871 0.1129

$HITO1_EDAD_GEST_SEM_REC
          Pr(1)  Pr(2)  Pr(3)  Pr(4)  Pr(5)  Pr(6)
class 1:      0 0.0000 0.2774 0.3734 0.2268 0.1224
class 2:      0 0.7875 0.2098 0.0000 0.0000 0.0027
class 3:      0 0.0113 0.6007 0.2615 0.1121 0.0144
class 4:      0 0.0202 0.3157 0.3964 0.2029 0.0648
class 5:      0 0.2755 0.2299 0.4904 0.0000 0.0043

$MACROZONA
          Pr(1)  Pr(2)  Pr(3)  Pr(4)  Pr(5)  Pr(6)
class 1:      0 0.2692 0.2011 0.2253 0.0895 0.2148
class 2:      0 0.4224 0.1552 0.1172 0.1351 0.1700
class 3:      0 0.6725 0.1154 0.0615 0.0781 0.0726
class 4:      0 0.6093 0.0989 0.0253 0.2396 0.0268
class 5:      0 0.4086 0.1608 0.1635 0.1206 0.1464

$PREV_TRAMO_REC
          Pr(1)  Pr(2)  Pr(3)  Pr(4)  Pr(5)
class 1:      0 0.0165 0.6578 0.3210 0.0047
class 2:      0 0.0615 0.6811 0.1927 0.0647
class 3:      0 0.5466 0.1775 0.2695 0.0064
class 4:      0 0.0151 0.6038 0.2733 0.1078
class 5:      0 0.1055 0.5341 0.3604 0.0000

Estimated class population shares 
 0.3811 0.1946 0.1759 0.0987 0.1498 
 
Predicted class memberships (by modal posterior prob.) 
 0.3782 0.1937 0.1494 0.1135 0.1652 
 
========================================================= 
Fit for 5 latent classes: 
========================================================= 
2 / 1 
            Coefficient  Std. error  t value  Pr(>|t|)
(Intercept)    -1.86652     0.15552  -12.002         0
outcome         1.41025     0.16503    8.545         0
========================================================= 
3 / 1 
            Coefficient  Std. error  t value  Pr(>|t|)
(Intercept)    -2.30304     0.29346   -7.848         0
outcome         1.76958     0.27174    6.512         0
========================================================= 
4 / 1 
            Coefficient  Std. error  t value  Pr(>|t|)
(Intercept)    -1.98117     0.23503   -8.429         0
outcome         0.78006     0.20284    3.846         0
========================================================= 
5 / 1 
            Coefficient  Std. error  t value  Pr(>|t|)
(Intercept)    -1.42421     0.19326   -7.369     0.000
outcome         0.61667     0.18216    3.385     0.001
========================================================= 
number of observations: 3789 
number of estimated parameters: 138 
residual degrees of freedom: 3651 
maximum log-likelihood: -26532.59 
 
AIC(5): 53341.19
BIC(5): 54202.29
X^2(5): 8561.743 (Chi-square goodness of fit) 
 
ALERT: estimation algorithm automatically restarted with new initial values 
 
Show code
save.image("data2_lca2_adj_imp.RData")
Show code
require(tidyverse)
sesion_info <- devtools::session_info()
print(Sys.time())
[1] "2023-05-06 23:10:54 -04"
Show code
dplyr::select(
  tibble::as_tibble(sesion_info$packages),
  c(package, loadedversion, source)
) %>% 
  DT::datatable(filter = 'top', colnames = c('Row number' =1,'Variable' = 2, 'Percentage'= 3),
              caption = htmltools::tags$caption(
        style = 'caption-side: top; text-align: left;',
        '', htmltools::em('Packages')),
      options=list(
initComplete = htmlwidgets::JS(
        "function(settings, json) {",
        "$(this.api().tables().body()).css({
            'font-family': 'Helvetica Neue',
            'font-size': '50%', 
            'code-inline-font-size': '15%', 
            'white-space': 'nowrap',
            'line-height': '0.75em',
            'min-height': '0.5em'
            });",#;
        "}")))