Bookmark and Share

Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: st: Looping through parallel lists


From   Russell Dimond <[email protected]>
To   [email protected]
Subject   Re: st: Looping through parallel lists
Date   Tue, 18 Mar 2014 16:15:40 -0500

Hi Caroline,

You might try something like this:

local file1 Cardiac
local vars1 cardiac_icd9 cardiac_icd9description

local file2 Concurrent
local vars2 cpt_con cpt_condescription

...

There are ways you could compress that, but I'd suggest keeping it simple.

Then loop over them with:

forval i=1/2 {
    use "$filepath/`file`i''", clear
    codebook case_number
    reshape wide `vars`i'', i(case_number) j(countvar)
    tab op_year
    save "$newfilepath/`file`i''", replace
}

(Change the 2 in the initial forval to match the number of files you have to work with.)

This involves macros within macros. On the first time through the loop i is 1, so `file`i'' first becomes `file1' and then Cardiac.

Note that I've changed the directory that the modified files are saved in. Never, ever, ever save your output over your input, or you can never run that do file again. And if it turns out you've made a mistake, you're up the proverbial creek.

Russell Dimond
Statistical Computing Specialist
Social Science Computing Cooperative
University of Wisconsin-Madison

On 3/18/2014 3:02 PM, Thirukumaran, Caroline Pinto wrote:
Hi,

I have several repetitive blocks of code like the ones below. How can
I use  -foreach- or -forvalues- commands for shortening such blocks of
code?

Example:
use "$filepath\Cardiac.dta", clear
codebook case_number
reshape wide cardiac_icd9 cardiac_icd9description, i(case_number) j(countvar)
tab op_year
save "$filepath\Cardiac.dta", replace

use "$filepath\Concurrent.dta", clear
codebook case_number
reshape wide cpt_con cpt_condescription, i(case_number) j(countvar)
tab op_year
save "$filepath\Concurrent.dta", replace

The difference in the two blocks lies in line 1 (filename), 3 (list of
multiple variables) and 5 (filename) of each block. I am using Stata
12.1 for Windows

Many thanks in advance,
Caroline
*
*   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/


Attachment: smime.p7s
Description: S/MIME Cryptographic Signature



© Copyright 1996–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index