lavaanExtra icon indicating copy to clipboard operation
lavaanExtra copied to clipboard

Indirect and Total Effect calculations

Open mzyphur opened this issue 3 years ago • 3 comments

Automated calculation of indirect and total effects would be very helpful in the time series and panel data cases. For example, with NLSY data in the years 1997 to 2002 for cigarette use and drinking behavior where the future depends on the past and effects 'propagate' over time along AR and CL paths in a cross-lagged panel model -- you can see that the total effects from the past to the future quickly blow up, for example, try to manually code an effects from 1997 to 2002 along all AR and CL path combinations required (I've only coded the 1997 --> 1999 effects as examples here, and you can download the data here):

library(lavaan)
nlsy<-read.csv("NLSY.csv", header=TRUE, na.strings=c("",".","NA","-999"))

ourModel <- '
  # AR terms
  cig02 ~ ar1_c*cig01
  cig01 ~ ar1_c*cig00
  cig00 ~ ar1_c*cig99
  cig99 ~ ar1_c*cig98
  cig98 ~ ar1_c*cig97
  drink02 ~ ar1_d*drink01
  drink01 ~ ar1_d*drink00
  drink00 ~ ar1_d*drink99
  drink99 ~ ar1_d*drink98
  drink98 ~ ar1_d*drink97
  
  # CL effect
  drink02 ~ cl1_dc*cig01
  drink01 ~ cl1_dc*cig00
  drink00 ~ cl1_dc*cig99
  drink99 ~ cl1_dc*cig98
  drink98 ~ cl1_dc*cig97
  cig02 ~ cl1_cd*drink01
  cig01 ~ cl1_cd*drink00
  cig00 ~ cl1_cd*drink99
  cig99 ~ cl1_cd*drink98
  cig98 ~ cl1_cd*drink97
  
  # Impulse responses
  c97.c98 := ar1_c
  c97.c99 := ar1_c^2 + cl1_dc*cl1_cd
  d97.d98 := ar1_d
  d97.d99 := ar1_d^2 + cl1_cd*cl1_dc
  c97.d98 := cl1_dc
  c97.d99 := cl1_dc*ar1_d + ar1_c*cl1_dc
  d97.c98 := cl1_cd
  d97.c99 := cl1_cd*ar1_c + ar1_d*cl1_cd
'
fit <- sem(ourModel, data = nlsy, mimic="Mplus", estimator="MLR")
summary(fit, fit.measures=TRUE, standardized = TRUE, rsquare=TRUE)

library(semTools)
monteCarloCI(fit, nRep = 10000, fast = TRUE, level = .95, plot = TRUE)

mzyphur avatar Aug 29 '22 23:08 mzyphur

Hi Mike, thanks a lot for opening this issue! It will help and motivate me to work on supporting this feature in the coming days/weeks hopefully. Because I agree with you that having to do this by hand every time would be unwieldy! Surely implementing this feature will be helpful to many people. I will update you when I have some developments on my side by commenting again on this issue.

rempsyc avatar Aug 29 '22 23:08 rempsyc

Just for my orientation, that is something you would probably implement in the write_lavaan() correct? Seems an interesting challenge by the way 👍

Buedenbender avatar Nov 11 '22 00:11 Buedenbender

Agreed, and it would be very helpful for the average researcher working with many indirect effects -- which can easily arise in even relatively simple models.

Cheers! Mike

mzyphur avatar Nov 11 '22 00:11 mzyphur