Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Create a copy of a column where the new column is offset by some fixed amount

Tags:

r

xts

I'm looking to create a copy of an existing column in a dataframe that is offset by a number of rows.

E.g. if column2 is a copy of column1 offset by 1, then

> dataframe
$column1
[1] 1 2 3 4 5

$column2
[1] 0 1 2 3 4

I've had some success with the following code:

offset7 <- rep(0, 7)
dataframe$column1.prev7 = c(offset7, dataframe$column1[1:(length(dataframe$column1)-7)])

However it starts giving errors if I offset by 30 or more. My data is long enough for this not to be a problem of the offset being larger than the number of rows. The error is:

Error in dataframe$column1[1:(length(dataframe$column1) - 30)] : 
  only 0's may be mixed with negative subscripts

Thanks in advance! A fast loop free version that plays nice with plyr would be preferred. The intention here is to break up the timeseries data into various lags up to a year and then analyse the results in various ways.

like image 752
psandersen Avatar asked Jan 21 '23 01:01

psandersen


1 Answers

Please use a proper time-series class for time-series operations. Popular favourites are zoo and xts both of which have plenty of documentation.

As a simple example, consider

> library(xts)
> foo <- xts(100:109, order.by=Sys.Date()+0:9)
> merge(foo,  l1=lag(foo,1), lm1=lag(foo,-1))
           foo  l1 lm1
2010-11-18 100  NA 101
2010-11-19 101 100 102
2010-11-20 102 101 103
2010-11-21 103 102 104
2010-11-22 104 103 105
2010-11-23 105 104 106
2010-11-24 106 105 107
2010-11-25 107 106 108
2010-11-26 108 107 109
2010-11-27 109 108  NA
> 

But just don't do it by hand. And do search here for '[r] xts' or [r] zoo' to search within the R tag.

like image 70
Dirk Eddelbuettel Avatar answered Feb 08 '23 09:02

Dirk Eddelbuettel