Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can declare your data as <code>ts()</code> and use <code>cbind()</code> and <code>diff()</code></p> <pre><code>data &lt;- 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') data &lt;- split(data,list(data$gvkey)) (newdata &lt;- do.call(rbind,lapply(data,function(data) { data &lt;- 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 </code></pre> <p>EDIT:</p> <p>Another way, without <code>split()</code> and <code>lapply()</code> (probably faster)</p> <pre><code>data &lt;- 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 &lt;- do.call(rbind,by(data, data$gvkey,function(data) { data &lt;- ts(data) ; cbind(data,Quarter=diff(data[,2]),Two.Quarter=diff(data[,2],2))})) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload