 Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.

# Re: st: Looping across observations (forwards and backwards)

 From Nick Cox To statalist@hsphsun2.harvard.edu Subject Re: st: Looping across observations (forwards and backwards) Date Sat, 24 Sep 2011 16:07:22 +0100

```When your program gets to

replace sinalt=`sinal' in `i'

evidently `sinal' is undefined so Stata sees

replace sinalt= in `i'

It tries first to interpret -in- as the name of a variable or scalar,
fails, and aborts with error.

Perhaps when you coded

if cod[j]==1 {

you meant

if cod[`j']==1 {

On Sat, Sep 24, 2011 at 3:28 PM, pedromfn <nakashimapedro@gmail.com> wrote:

> My database looks like:
>
> obs cod pr qt sinalt
> 1 1 1.4 100 .
> 2 2 1.5 100 .
> 3 1 1.5 95 .
> 4 1 1.4 100 .
> 5 3 1.5 100 .
>
> and I want to replace observations of sinalt in which cod==3, according to
> the following rule:
> 1) Go across observations looking for observations in which cod=3
> 2) In the above example, the first observation is observation 5, in which
> pr=1.5 and qt=100. Once that observation was found, go backwards
> through observations looking for the first observation j in which
> pr[j]==pr & qt[j]==qt. In the example, j=2.
> 3) Replace sinalt=`sinal' , where the macro sinal is defined as:
>     if cod[j]==1, store in the local sinal the value 1
>     if cod[j]==2, store in the local sinal the value -1
> 4) Once last replace was done, look for the next observation in which cod==3
> and do the same thing.
>
> I wrote the following do-file, but it didn't work:
>
> forvalues i=1/`=_N' {
>        if cod[`i']==3{
>                local j=`i'-1
>                if pr[`j']==pr[`i'] & qt[`j']==qt[`i'] {
>                        if cod[j]==1 {
>                                local sinal 1
>                        }
>                        else if cod[`j']==2 {
>                                local sinal -1
>                        }
>                        else {
>                                local sinal
>                        }
>                }
>                else {
>                        while pr[`j']!=pr[`i'] | qt[`j']!=qt[`i'] {
>                                local --j
>                        }
>                }
>        replace sinalt=`sinal' in `i'
>        }
> }
>
> ERROR: