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

I am looking to create a copy of an existing column in a data frame that is offset by a row of rows.

eg. if column2 is a copy of column 1 with an offset of 1, then

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

$column2
[1] 0 1 2 3 4

I 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 to make mistakes if I make up for 30 or more. My data is long enough so that this is not an offset problem exceeding the number of rows. Error:

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

Thanks in advance! A free cycle fast version that plays well with plyr would be preferable. The goal here is to break down the timeseries data into various delays up to a year, and then analyze the results in various ways.

+3
1

, . zoo xts .

> 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
> 

. '[r] xts' [r] zoo ' R.

+8

Source: https://habr.com/ru/post/1775739/


All Articles