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

# st: RE: Fwd: Problem with lag operator

 From Nick Cox To "'statalist@hsphsun2.harvard.edu'" Subject st: RE: Fwd: Problem with lag operator Date Tue, 15 Feb 2011 15:19:47 +0000

```"doesn't work" is not diagnostic. I once tabulated about 20 different meanings encountered on this list, including "is illegal", "does not do what I would like", "does not converge before I go home" and "is not what my thesis committee would prefer to see".

However, there is at least one evident flaw in your code. Subscripts before the equals (assignment) sign are illegal. As in any case [_n] is the default subscript you lose nothing.

bysort id (n): replace start = end[_n-1] if start == end[_n-1]+1

appears to be what you are asking for.

bysort id (n) : gen checkthisfirst = end[_n-1] if start == end[_n-1] + 1

would be safer. That is, check it first to see if it is what you want.

Nick
n.j.cox@durham.ac.uk

Eleonora Paesen

I have the following data set and would like to replace the values in
START by the one on the previous line of END if they are of one unit
apart (within the same id).
For example I would like to replace the value of 1184 for the second
observation of id1 by the value of 1183 in first observation of END;

I have tried with this:

bysort id (n): replace start[_n]=end[_n-1] if start[_n]==end[_n-1]+1
It doesn't work.
Would you have any suggestions on this?

list id n start end in 1/23, sepby(id)

+-----------------------+
| id   n   start    end |
|-----------------------|
1. |  1   1     956   1183 |
2. |  1   2    1184      . |
|-----------------------|
3. |  2   1    1064   1085 |
4. |  2   2    1086   1163 |
5. |  2   3    1164   1193 |
6. |  2   4    1194      . |
|-----------------------|
7. |  3   1     976   1184 |
8. |  3   2    1185      . |
|-----------------------|
9. |  4   1     993      . |
|-----------------------|
10. |  5   1    1034   1149 |
11. |  5   2    1150      . |
|-----------------------|
12. |  6   0       0      0 |
|-----------------------|
13. |  7   1    1009   1035 |
14. |  7   2    1036   1061 |
|-----------------------|
15. |  8   1     968    969 |
16. |  8   2     970      . |
|-----------------------|
17. |  9   1     945    955 |
18. |  9   2     956    974 |
19. |  9   3     976   1027 |
20. |  9   4    1028   1029 |
21. |  9   5    1030   1131 |
22. |  9   6    1194      . |
|-----------------------|
23. | 10   1     918      . |
+-----------------------+

*
*   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/
```