Bookmark and Share

Notice: On March 31, it was announced that Statalist is moving from an email list to a forum. The old list will shut down at the end of May, and its replacement, statalist.org is already up and running.


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

Re: st: How to use functions within variable names


From   daniel klein <klein.daniel.81@googlemail.com>
To   statalist@hsphsun2.harvard.edu
Subject   Re: st: How to use functions within variable names
Date   Wed, 17 Aug 2011 10:09:16 +0200

Sdfsdfsadfsf ,

please note that it is practice on Statalist to use real names (c.f.
http://www.stata.com/support/faqs/res/statalist.html#tojoin).

Regarding your queston, there are two points to mention.

1. You will have to make sure that the expression you are using is
evaluated "on the fly" while looping, as Maarten already has shown.
Stata will evaluate

forvalue i=1(1)100 {
   replace b_`i'= a[c+`i']
}

to read

forvalue i=1(1)100 {
   replace b_1= a[7+1]
}

the first time through the loop, meaning that Stata evaluates the
local i but not the expression as a hole. To evaluate the expression
you will need to code

forvalue i=1(1)100 {
   loc expr = a + `i'
   replace b_`i'= a[`expr']
}

or short

forvalue i=1(1)100 {
   replace b_`i'= a[`= c+`i'']
}

2. Note however, that c will always be evaluated to 7, or whichever
value the first observation of c holds. You probably did not expect
this behavior so you migth have to code something like this

forvalue i=1(1)100 {
   replace b_`i'= a[`= c[`i'] + `i']
}

It might be more convenient to use two parallel lists in the loop.
Here (http://www.stata.com/support/faqs/lang/parallel.html) is how you
do that.

Given little information, I cannot comment on the appropriatness of
your approach to solve the undelying problem.

Best
Daniel
*
*   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–2014 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   Site index