# Problem generating a lagged variable

#### larip

##### New Member
Hey!

My data set is sorted by company name and month. I have generated a variable called IV for each company (i=1,2,3.....6000) for each month (i=1,2,3,...12). Now I want to generate a lagged variable lag1 on monthly basis.

Please find below the desired outline:

IV lag1
12 -
12 -
12 -
12 -
10 12
10 12
10 12
10 12
8 10
8 10
4 8
4 8
50 4
50 4
50 4
50 4

This is how I have approached the problem:
. sort permno month
. by permno: gen lag1=IVj[_n-1]

... and this is the outcome:

IV lag1
12 -
12 12
12 12
12 12
10 12
10 10
10 10
10 10
8 10
8 8
4 8
4 4
50 4
50 50
50 50
50 50

Thank you!

#### remat

##### New Member
Hi larip!

Can you try doing this using the following code?

gen laggedIV = L4.IV

#### larip

##### New Member
Hi larip!

Can you try doing this using the following code?

gen laggedIV = L4.IV
Hey Remat,

. gen laggedIVj=L4.IVj
time variable not set

What does L4. mean? Did I do something wrong?

#### remat

##### New Member
Hi larip,

Assuming your data is time series, you must declare a variable (t, say) to be a time variable.

E.g. . gen t = _n
tsset t, monthly

However, looking at your first post, try tweaking your formula as [_n-4], since you want to lag back 4 observations. Let me know if it worked.

#### larip

##### New Member
I am using panel data. The problem with lagging back is the fact that I cannot fix the number of observations, i.e. [_n-4], because there is variation in monthly observations. Find below more informative example of my data set:

Month IVj Lag1
1 10 -
1 10 -
1 10 -
2 12 10
2 12 10
2 12 10
2 12 10
3 8 12
3 8 12
3 8 12
4 15 8
4 15 8
5 7 15
6 1 7
7 5 1
7 5 1

Therefore, I should tell Stata to count the number of observations in the last month, i.e. gen lag1=IVj[_n-(count if month-month[_n-1]=1)], which would make the lag component dynamic.

Last edited:

#### larip

##### New Member
SOLVED: Problem generating a lagged variable

In case someone has a similar kind of problem, here's one way to do it:

. gen lag1=IVj[_n-1] if month==month[_n-1]+1
. replace lag1=lag1[_n-1] if missing(lag1)
. replace lag1=IVj if lag1==.