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 on April 23, and its replacement, 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 <>
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.

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 ( is how you
do that.

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

*   For searches and help try:

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