I have an R dataframe that looks something like this:
| Date | Price UP | Price Down |
| ------------ | ------------ | ------------ |
| 2023-01-01 | NA | NA |
| 2023-01-02 | 10 | NA |
| 2023-01-03 | NA | NA |
| 2023-01-04 | NA | 4 |
| 2023-01-05 | NA | 3 |
| 2023-01-06 | 10 | NA |
| 2023-01-07 | NA | 2 |
I tried using for loop to assign 'Phase numbers' every time the price goes up and then comes down. For example if the price UP is 10 and the next price down after that is 4, then the dates between them are Phase 1, and so on we mark Phase 2, 3, ...n.
Can we have a dplyr friendly way to get the same result?
The final output should look something like this:
| Date | Price UP | Price Down | PhaseIndicator |
| ------------ | ------------ | ------------ | ------------ |
| 2023-01-01 | NA | NA | |
| 2023-01-02 | 10 | NA | Phase 1 |
| 2023-01-03 | NA | NA | Phase 1 |
| 2023-01-04 | NA | 4 | Phase 1 |
| 2023-01-05 | NA | 3 | |
| 2023-01-06 | 10 | NA | Phase 2 |
| 2023-01-07 | NA | 2 | Phase 2 |
1条答案
按热度按时间0tdrvxhp1#
这里我建议告诉我它是否符合
这里,相位数由价格上涨的次数
row_number(up>0)
确定,随着fill()
,相位数(Nup)被结转到下一个值