r - How to calculate percentage change from different rows over different spans -
r - How to calculate percentage change from different rows over different spans -
i trying calculate percentage alter in cost quarterly info of companies recognized gvkey
(1001, 1384, etc...). , 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 trying add together 8 columns showing 1 quarter return, 2 quarter return, etc. way 8 quarters. have been able calculate 1 quarter homecoming each prccq using delt
function of quantmod
, ddply
of plyr
, , able 2 quarter homecoming using same code altering k
.
ddply(data, "gvkey", transform, deltacol = delt(prccq,k=2))
however, equation not allow me go higher k=2
without giving me error of differing number of rows 2,3. i've tried using many alternate methods dint work. there function can plug ddply
code have replace delt
or maybe alternative line of code display 8 quarters of homecoming in individual columns?
you can declare info ts()
, utilize cbind()
, diff()
data <- read.table(header=t,text='gvkey prccq 1004 23.750 1004 13.875 1004 11.250 1004 10.375 1004 13.600 1004 14.000 1004 17.060 1005 8.150 1005 7.400 1005 11.440 1005 6.200 1005 5.500 1005 4.450 1005 4.500 1005 8.010') info <- split(data,list(data$gvkey)) (newdata <- do.call(rbind,lapply(data,function(data) { info <- ts(data) ; cbind(data,quarter=diff(data[,2]),two.quarter=diff(data[,2],2))}))) data.gvkey data.prccq quarter two.quarter [1,] 1004 23.750 na na [2,] 1004 13.875 -9.875 na [3,] 1004 11.250 -2.625 -12.500 [4,] 1004 10.375 -0.875 -3.500 [5,] 1004 13.600 3.225 2.350 [6,] 1004 14.000 0.400 3.625 [7,] 1004 17.060 3.060 3.460 [8,] 1005 8.150 na na [9,] 1005 7.400 -0.750 na [10,] 1005 11.440 4.040 3.290 [11,] 1005 6.200 -5.240 -1.200 [12,] 1005 5.500 -0.700 -5.940 [13,] 1005 4.450 -1.050 -1.750 [14,] 1005 4.500 0.050 -1.000 [15,] 1005 8.010 3.510 3.560
edit:
another way, without split()
, lapply()
(probably faster)
data <- read.table(header=t,text='gvkey prccq 1004 23.750 1004 13.875 1004 11.250 1004 10.375 1004 13.600 1004 14.000 1004 17.060 1005 8.150 1005 7.400 1005 11.440 1005 6.200 1005 5.500 1005 4.450 1005 4.500 1005 8.010') newdata <- do.call(rbind,by(data, data$gvkey,function(data) { info <- ts(data) ; cbind(data,quarter=diff(data[,2]),two.quarter=diff(data[,2],2))}))
r statistics plyr quantmod
Comments
Post a Comment