Stata The Stata listserver
[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

st: Re: looping with a command

From   Christopher F Baum <>
Subject   st: Re: looping with a command
Date   Thu, 14 Oct 2004 07:57:44 -0400

Here is a quick-n-dirty that constructs the appropriate input statement. It should also check to see that the lists are of the right length. It could easily be extended to deal with the generates, sums, etc.

capt program drop devra
program devra,rclass
syntax ,Vars(integer) Len(numlist) At(numlist) Infix(string) Prefix(string)
di "want to read and massage `vars' vars"
di "with lengths `len'"
di "at locns `at'"
local inf "`prefix'"
local infend " using `infix'"
forv i=1/`vars' {
local l : word `i' of `len'
local a : word `i' of `at'
local inf "`inf' str`l' a`i' `a'"
local inf "`inf' `infend'"
file open devra using "/tmp/", write replace
file write devra "`inf'"
file close devra

To execute:
. devra, vars(3) len(3 5 4) at(21 39 48) infix(rawdata.txt) prefix(infix str name 1-5 str id 6-10)
want to read and massage 3 vars
with lengths 3 5 4
at locns 21 39 48

. type /tmp/
infix str name 1-5 str id 6-10 str3 a1 21 str5 a2 39 str4 a3 48 using rawdata.txt


On Oct 14, 2004, at 2:33, Devra wrote:

For want of a better, term, I describe my question as how to loop inside a
single command. I don't see how to make foreach or forvalues work for
this kind of problem, nor has browsing the programming manual, the FAQs, or
Nick Cox's Stata Journal articles on lists turned up a solution.

The command uses the arguments x1...xN, and I would like to be able to
treat N as a variable. For instance, I need to read a fixed-format text
file which contains a number N of string variables; N varies each time I
run the program. The following infix statement does the job for N=5:

infix ///
str name 124-143 ///
str id 144-152 ///
str a1 217 str a2 218 str a3 219 str a4 220 str a5 221 ///
using rawdata.txt

Kit Baum, Boston College Economics

*   For searches and help try:

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