I have the following data frame.
date id value
2012-01-01 1 0.3
2012-01-01 2 0.5
2012-01-01 3 0.2
2012-01-01 4 0.8
2012-01-01 5 0.2
2012-01-01 6 0.8
2012-01-01 7 0.1
2012-01-01 8 0.4
2012-01-01 9 0.3
2012-01-01 10 0.2
There are several dates and for each date, I have 10 id values as shown above and a value field. What I would like to do is for every id find the previous n values in the “value” field. For example if n = 3 then I want the output to be as follows.
date id value value1 value2 value3
2012-01-01 1 0.3 NA NA NA
2012-01-01 2 0.5 NA NA NA
2012-01-01 3 0.2 NA NA NA
2012-01-01 4 0.8 0.2 0.5 0.3
2012-01-01 5 0.2 0.8 0.2 0.5
...
Is there an easy way to get to this either through plyr or using mapply? Thanks much in advance.
You can do this quite easily using base functions:
Result
Made a mistake here previously – here is an
sapplyversion in a function:Which gives just this:
You could then apply this to each set of dates in your data like this:
Which gives a bunch of lists for each date set. You could rowbind these up for adding back to your data set with: