Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.
From | Nick Cox <njcoxstata@gmail.com> |
To | statalist@hsphsun2.harvard.edu |
Subject | Re: st: Use matrix for save results of looping |
Date | Sun, 30 Sep 2012 16:46:44 +0100 |
Various fixes to your code are included here. clear all set mem 800m global path "E:/data/ENE" global pathdo "C:/gonzalo/" cd "${path}" local bases ond1996 ond1997 local nbases : word count `bases' matrix P = J(`nbases',1,.) matrix rowname P = `bases' matrix colname P = Junior local i = 1 foreach base of local bases { use `base', clear summ p12_2 if p12_2>48 local hora=r(sum_w) summ estado if estado==1 matrix P[`i',1] = `hora'/r(sum_w)*100 local ++i } matrix list P, format(%2.1f) Main points: 1. You should set up a matrix of the right size first, then fill in its results. 2. I guess that you want display to 1 decimal place, but -round(<whatever>, 0.1)- cannot produce that reliably for reasons explained in many places under the heading "precision". See e.g. Bill Gould's blog posts on precision at blog.stata.com 3. For export, see -mat2txt- from SSC. Secondary points: 4. Forward slashes are safer, even under Windows. SJ-8-3 pr0042 . . . . . . . Stata tip 65: Beware the backstabbing backslash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . N. J. Cox Q3/08 SJ 8(3):446--447 (no commands) tip to use forward slash instead of backslash for directory and file names 5. Don't evaluate macros when you don't need to. SJ-8-4 pr0045 . . . . . . . . Stata tip 70: Beware the evaluating equal sign . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . N. J. Cox Q4/08 SJ 8(4):586--587 (no commands) tip explaining the pitfall of losing content in a macro because of limits on the length of string expressions 6. Various simplifications included in the code above. Nick On Sun, Sep 30, 2012 at 4:15 PM, Gonzalo DURAN SANHUEZA <giduran@puc.cl> wrote: > by each database, I want save one scalar in a > unique matrix. I use a foreach command for load each database. The > problem with my instruction is that only retrieves the scalar for the > latest database. I need two things: 1) a unique matrix that retrieves > the scalars defined in all the loop and 2) if exist some instruction > for export the matrix into a csv file. Thanks > > This is the do > > clear all > set mem 800m > global path="E:\data\ENE" > global pathdo="C:\gonzalo\" > cd "${path}" > local bases ond1996 ond1997 > > foreach base of local bases { > if "`base'"=="ond1996" { > use ond1996, clear > } > if "`base'"=="ond1997" { > use ond1997, clear > } > summ p12_2 if p12_2>48 > local hora=r(sum_w) > summ estado if estado==1 > scalar k=round(`hora'/r(sum_w)*100, .1) > matrix define P=(k) > matrix rowname P=`base' > matrix colname P=Junior > matrix list P > } * * For searches and help try: * http://www.stata.com/help.cgi?search * http://www.stata.com/support/faqs/resources/statalist-faq/ * http://www.ats.ucla.edu/stat/stata/