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]

st: RE: Looping gen sequentially over datasets


From   Joe Canner <[email protected]>
To   "[email protected]" <[email protected]>
Subject   st: RE: Looping gen sequentially over datasets
Date   Wed, 25 Sep 2013 16:54:36 +0000

Alex,

You are probably right that a -foreach- loop will be required.  Can you provide some information on the naming convention for each file (i.e., what is similar and what is different) so that we can recommend the right solution?  In the meantime, here is a general solution:

. local id=0
. foreach file in "file1" "file2" ... {
.  use `file', clear
.  local ++id
.  gen School_ID=`id'
.  save , replace
. } 

If your only use for this is to have a unique identifier after you combine the data sets, also consider using the -gen(newvar)- option of the -append- command.  This can be used to identify which data set contributed to the conglomerated data set and you can use that to generate unique IDs after the append, instead of using the looping method above to add an identifier to each dataset.

Regards,
Joe Canner
Johns Hopkins University School of Medicine

-----Original Message-----
From: [email protected] [mailto:[email protected]] On Behalf Of Alex Sutherland
Sent: Wednesday, September 25, 2013 12:27 PM
To: [email protected]
Subject: st: Looping gen sequentially over datasets

Dear Statalisters,

I am trying to generate sequential ID variables over a series of datasets.
There are 40 datasets representing 40 schools and I want to generate an ID variable for each school (ranging from 1-40) without the need to open and edit each file manually. (I'm likely to have to repeat this process later and I want to combine the datasets once the ID variable is created, hence the need for unique identifiers for each school). I keep thinking it's going to involve a foreach loop over the datasets combined with another loop (forval?), but then I'm up against the limits of my Stata-ing so any help gratefully received.

Thanks in advance,

Alex

Dr. Alex Sutherland
Research Methods Associate,
Social Sciences' Research Methods Centre (SSRMC) http://www.ssrmc.group.cam.ac.uk/

Office 3.12
Institute of Criminology,
University of Cambridge,
Sidgwick Site
CB3 9DA
Tel: +44 (0)1223 746519
[email protected]
http://www.crim.cam.ac.uk/people/academic_research/alex_sutherland/

*
*   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/

*
*   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/


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