Is there any way I can create a variable which depends on its earlier observation in R?
In the below example, the column 'asset' should be depreciated by 1,67% (20%/12) per time period (t)
The first 'end result' is = 'asset - depr'
The problem I face is that from row 2, the value in 'end-result' must depend on the 'end-result' in the previous time period.
From t=2 and onwards, depr. is found as 'end-result, t-1' * 1,67%
Thank you!
(This is how the final product should look) - also sorted on PERMNO (ID)
t id asset depr. end_result
1 10010 45145 752 44393
2 10010 45145 740 43653
3 10010 45145 728 42925
4 10010 96730 1575 92935
5 10010 96730 1549 91386
6 10010 96730 1523 89863
7 10010 145511 2311 136333
8 10010 145511 2272 134061
9 10010 145511 2234 131827
10 10010 190986 2955 174347
11 10010 190986 2906 171441
12 10010 190986 2857 168584
1 10020 20050 334 19716
2 10020 20050 329 19387
3 10020 20050 323 19064
4 10020 50411 824 48601
5 10020 50411 810 47791
6 10020 50411 797 46995
7 10020 120154 1946 114792
8 10020 120154 1913 112879
9 10020 120154 1881 110998
10 10020 173575 2740 161678
11 10020 173575 2695 158984
12 10020 173575 2650 156334
taking this sample data
Approach-1 Base R method
the additions during the year
by usingave()
in base R. Actually, your asset value column is like a cumulative value of asset and it has to be reduced like only additions during the month. (step-1)Reduce()
with agrumentaccumulate = TRUE
. This will help in generation of your residual value column.(step-2)Check the results
Approach-2
dplyr
approach.Which is exactly same as your desired output
Approach-3 using
purrr::accumulate()