## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

## ----setup--------------------------------------------------------------------
library(plavaan)
library(lavaan)

## -----------------------------------------------------------------------------
# Load the PoliticalDemocracy data
data("PoliticalDemocracy", package = "lavaan")
# Configural invariance (pretend y7 is not available in dem65),
# and freely estimated latent means and variances
config_mod <- "
  dem60 =~ y1 + y2 + y3 + y4
  dem65 =~ y5 + y6 +      y8
  dem60 ~~ dem65
  dem60 ~~ 1 * dem60
  dem65 ~~ NA * dem65
  dem60 ~ 0
  dem65 ~ NA * 1
  y1 ~~ y5
  y2 ~~ y6
  y4 ~~ y8
"
fit_dry <- cfa(config_mod, data = PoliticalDemocracy, auto.fix.first = FALSE,
               do.fit = FALSE)

## -----------------------------------------------------------------------------
parTable(fit_dry)
# Create matrix to indicate the same item loadings across groups/time in columns for
# penalization on the pairwise differences
ld_mat <- rbind(1:4, c(5:6, NA, 7))
int_mat <- rbind(21:24, c(25:26, NA, 27))
fit_pen <- penalized_est(
  fit_dry, w = .03, pen_diff_id = list(loadings = ld_mat, intercepts = int_mat),
  se = "robust.huber.white"
)
summary(fit_pen)

## ----echo=TRUE, eval=FALSE----------------------------------------------------
# # export to Mplus
# write.table(PoliticalDemocracy,
#             file = "inst/mplus/PoliticalDemocracy.dat",
#             row.names = FALSE, col.names = FALSE)
# # Mplus syntax
# mplus_syntax <- "
# TITLE:  Penalized invariance CFA model;
# DATA:   FILE = PoliticalDemocracy.dat;
# VARIABLE:
#         NAMES = y1-y8;
#         USEVARIABLES = y1-y6 y8;
# MODEL:  dem60 BY y1-y4* (l1_1-l1_4);
#         dem65 BY y5-y6* (l2_1-l2_2)
#                  y8* (l2_4);
#         dem60@1;
#         dem65*1;
#         [dem60@0];
#         [dem65*0];
#         [y1-y4] (i1_1-i1_4);
#         [y5-y6] (i2_1-i2_2);
#         [y8] (i2_4);
#         y1 WITH y5;
#         y2 WITH y6;
#         y4 WITH y8;
# MODEL PRIOR:
#         DO(#,1,2) DIFF(l1_# , l2_#) ~ ALF(0,1);
#         DO(#,1,2) DIFF(i1_# , i2_#) ~ ALF(0,1);
#         DIFF(l1_4 , l2_4) ~ ALF(0,1);
#         DIFF(i1_4 , i2_4) ~ ALF(0,1);
# "
# # Save Mplus syntax
# writeLines(mplus_syntax, con = "inst/mplus/penalized_invariance.inp")
# # Run Mplus
# system("cd inst/mplus && mplus penalized_invariance.inp")

