Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • polychoric in a for loop

    Dear Statalisters
    I am trying to run a polychoric factor analysis for 4 variables (perma prinActSta union woutwrk) by state. I have 35 states and the variables are binary and ordered categorical, so I wrote a for loop for it which is as follows:

    forval j = 1/35 {
    polychoric perma prinActSta union woutwrk if STATE==`j'
    display r(sum_w)
    local N`j' = r(sum_w)
    matrix r`j' = r(R)
    factormat r`j' ,n($N`j') factors(1) ml
    predict Wbp`j' if STATE==`j'
    }

    Stata seems to execute the first 4 lines correctly, however in the 5th line i.e the factormat, the number of observations change so it's executed incorrectly. Stata does not update the number of observations in n($N`j').

    What I would ideally like to do is run the following for 35 states.


    polychoric perma prinActSta union woutwrk if STATE==1
    display r(sum_w)
    local N1 = r(sum_w)
    matrix r1 = r(R)
    factormat r1 ,n($N1) factors(1) ml
    predict Wbp1 if STATE==1

    Is there any way I could update the local in the for loop?
    Best Regards
    Sayli


  • #2
    You are referring to the local macros N1, N2, etc. with $ (i.e. you treat them as if they were global macros).

    Modifiying your command according to the following example should work (note that in the Statalist Forum you should wrap Stata commands with code tags):

    Code:
    use http://www.stata-press.com/data/r15/familyvalues, clear
    
    gen state = runiform()
    recode state (min/.2=1) (.2/.4=2) (.4/.6=3) (.6/.8=4) (.4/max=5), gen(statei)
    
    levelsof statei, local(s)
    foreach j of local s {
       polychoric RS056-RS063 if statei==`j'
       display r(sum_w)
       local N`j' = r(sum_w)
       matrix r`j' = r(R)
       factormat r`j', n(`N`j'') factors(2) ml
       rotate, promax
       predict Wbp1`j' Wbp2`j' if statei==`j'
    }
    I created a variable statei to show how to loop over each value of statei. Note that the use of levelsof guarantees that you will use all values of statei (even if the values are not consecutive).

    Additionally, I modified the factor command to extract two factors and rotated the factor solution before generating factor scores for two factors.
    Last edited by Dirk Enzmann; 31 Jul 2018, 11:14.

    Comment

    Working...
    X