Statalist


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

Re: st: using a string variable with use and save command


From   Kushan Thakkar <[email protected]>
To   [email protected]
Subject   Re: st: using a string variable with use and save command
Date   Tue, 13 Oct 2009 01:54:04 -0400

my files have structured names such as file1.dta, file2.dta, etc

so would the syntax be something like:

forvalues i=1(1)10 {
       use "\user\kushan\file"`i'".dta", clear
       // do something
       save "\user\kushan\file"`i'".dta", replace
}

i guess I am not clear about the syntax of the part where i
concatenate strings to create a filename.

would it be more appropriate to store string as variables and then concatenate?

such as,

gen fileprefix = "\user\kushan\file"
gen filesuffix = ".dta"

forvalues i=1(1)10 {
          use fileprefix`i'filesuffix, clear
          // do something
}

Thanks for your help.


On Mon, Oct 12, 2009 at 11:41 PM, Joseph McDonnell <[email protected]> wrote:
> On Tue, Oct 13, 2009 at 11:53 AM, Kushan Thakkar <[email protected]> wrote:
>> I want to write a program that reads a list of files one by one
>> (through a for loop) while making changes. In order to do so, i will
>> need to supply a the file name as a variable with the use command.
>>
>> For example:
>>
>> gen filestr = "file name here"
>> gen fileno = 1
>> gen infile = filestr + fileno
>> use infile, clear
>>
>> Could somebody please help me with the correct syntax for doing this?
>>
>> Thanks.
>> Kushan
>> *
>> *   For searches and help try:
>> *   http://www.stata.com/help.cgi?search
>> *   http://www.stata.com/support/statalist/faq
>> *   http://www.ats.ucla.edu/stat/stata/
>>
>
> Kushan
>
> looks like you need to use macros and forvalues/foreach loop. If your
> files have "structured" names (e.g. myfile1, myfile2,...myfile10) you
> can use the following code...
>
> forvalues i=1(1)10 {
>        use myfile`i', clear
>        // do something
>        save myfile`i', replace
> }
>
> Of course, you may wish to save under another name.
>
> If the names are less "regular", you can list them in a macro and then
> have Stata step through the list.
>
> local flist "a b c"
> foreach f in `flist' {
>        use `f', clear
>        // do something
>        save `f', replace
> }
>
> There is a "for" command but is out of date and should not be used.
>
> HTH
>
> Joseph
>
> *
> *   For searches and help try:
> *   http://www.stata.com/help.cgi?search
> *   http://www.stata.com/support/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/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/



© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index