Announcement

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

  • Saving multiple simulated data using foreach command

    Dear all,

    I am a newbie in a simulation study. Here I created one simulated data using foreach command (n=500 t=5). I would also like to create 500 data and save them using this code. Would you help me to do so?

    Thank you,


    Code:
    clear
    drop _all
    
    
    global obs        = 500        
    global waves     = 5                 
    global corrXY    = .5    
    global corrXZ     = 0        
    global corrYZ     = 0     
    
    
    foreach endox of numlist .1  {        
    foreach endoy of numlist .2  {                                
    foreach autox of numlist .2 {                        
    foreach autoy of numlist .3 {                                        
    foreach unob of numlist .5 {    
    
    global autox    = `autox'    
    global endox    = `endox'    
    global endoy    = `endoy'    
    global autoy    = `autoy'    
    global betax    = 1            
    global betaxlag    = 1            
    global betay    = 1            
    global betaylag    = 1            
    global unob     = `unob'    
    
    
    mat C =(1, $corrXY,$corrXZ \ $corrXY,1,$corrYZ \ $corrXZ,$corrYZ,1)
    corr2data X Y Z, n($obs) corr(C)
    
    
    gen id = _n 
    expand = $waves 
    bysort id: generate wave = _n  
    replace wave = wave-1  
    
    foreach var of varlist X Y Z {        
        replace `var' = . if wave >0    
    }
    
    xtset id wave
    reshape wide X Y Z , i(id) j(wave) 
    
            
    gen x0 = X0 + rnormal()           
    gen y0 = Y0 + rnormal()            
    gen z0 = Z0 + rnormal(0, 1.73)  
    
    
    foreach num of numlist 1/$waves{    // starts from wave 1        
    gen x`num' = 3+ $autox* x`=`num'-1' + rnormal(0,1)     + ///
    $endox* y`=`num'-1' + ($unob*z0) 
    gen y`num' = 4+ $autoy* y`=`num'-1' + rnormal(0,1)     + ///
    $endoy* x`=`num'-1' + ($unob*z0) 
    
    }
    }
    }
    }
    }}

    Sean

  • #2
    You have accidentally posted your topic in Statalist's Mata Forum, which is used for discussions of Stata's Mata language. Your question will see a much larger audience if you post it in Statalist's General Forum. Your use of a Stata matrix command is different than Stata's Mata programming language, as the output of help matrix tells us.

    Beyond the matrix commands, Stata has a complete matrix programming language, Mata, that provides more advanced matrix functions, support for complex matrices, fast execution speed, and the ability to directly access Stata's data, macros, matrices, and returned results

    Comment

    Working...
    X