I am trying to calculate the percentage change in price for quarterly data of companies recognized by a gvkey
(1001, 1384, etc...). and it's corresponding quarterly stock price, PRCCQ
.
gvkey PRCCQ
1 1004 23.750
2 1004 13.875
3 1004 11.250
4 1004 10.375
5 1004 13.600
6 1004 14.000
7 1004 17.060
8 1004 8.150
9 1004 7.400
10 1004 11.440
11 1004 6.200
12 1004 5.500
13 1004 4.450
14 1004 4.500
15 1004 8.010
What I am trying to do is add 8 columns showing 1 quarter return, 2 quarter return, etc. all the way to 8 quarters. I have been able to calculate 1 quarter return for each PRCCQ by using the delt
function of quantmod
and ddply
of plyr
, and I was also able to get the 2 quarter return using the same code by altering k
.
ddply(data, "gvkey", transform, DeltaCol = Delt(PRCCQ,k=2))
However, this equation will NOT allow me to go higher than k=2
without giving me an error of differing number of rows 2,3. I've tried using many alternate methods now but dint work. Is there a function I can plug into the ddply
code I have to replace Delt
or maybe another completely alternative line of code to display all 8 quarters of return in individual columns?