I'm dealing with a dataset in the following format:
var1 |
quantity |
a |
1000 |
b |
900 |
c |
850 |
d |
500 |
e |
1000 |
f |
600 |
g |
500 |
h |
1500 |
i |
1450 |
The data is sorted by year and quantity. So in the example above, observations 1, 2, 3, and 4 are all from the same year. You can tell that a new year has begun because the value of variable quantity in observation 5 is higher than its value in observation 5. I'm trying to generate a new variable called
year which should go up by 1 every time this happens. I have already attempted doing something along these lines, where the first year is year 0:
Code:
foreach x of varlist quantity {
gen year = 0
replace year = year+1 if `x'[_n] > `x'[_n-1]
}
This sets the year variable to 1 on the observations where the quantity variable is higher than the value in the previous observation. I'm looking for a way to make the dataset look like this:
var1 |
quantity |
year |
a |
1000 |
0 |
b |
900 |
0 |
c |
850 |
0 |
d |
500 |
0 |
e |
1000 |
1 |
f |
600 |
1 |
g |
500 |
1 |
h |
1500 |
2 |
i |
1450 |
2 |
Any help is appreciated.
0 Response to Creating a year variable by counting the amount of times the value of another variable is higher than the previous observation's value
Post a Comment