I am trying to create some code to determine if a certain statement is true for three consecutive years. This statement is, for example, that the amount needs to be negative for three consecutive years. Only if that is true, the third row should be marked in a new column with a 1, otherwise, the rows should be marked as a 0.
To further elaborate on what I try to do, I've created the following dataset:
| ID | Year | Amount |
|---|---|---|
| 001 | 2022 | 2 |
| 001 | 2021 | -9 |
| 001 | 2020 | -10 |
| 001 | 2019 | -16 |
| 001 | 2018 | -20 |
| 002 | 2022 | 400 |
| 002 | 2021 | 300 |
| 002 | 2020 | -200 |
| 002 | 2019 | -600 |
| 002 | 2018 | -500 |
And the outcome should look somewhat like this:
| ID | Year | Amount | Y/N |
|---|---|---|---|
| 001 | 2022 | 2 | 0 |
| 001 | 2021 | -9 | 1 |
| 001 | 2020 | -10 | 1 |
| 001 | 2019 | -16 | 0 |
| 001 | 2018 | -20 | 0 |
| 002 | 2022 | 400 | 0 |
| 002 | 2021 | 300 | 0 |
| 002 | 2020 | -200 | 1 |
| 002 | 2019 | -600 | 0 |
| 002 | 2018 | -500 | 0 |
Does anybody know how I could code this?