Search code examples
rdataframetime-seriesxts

How to replace every six row in a data set with its lag starting from 7th row


I want to replace every sixth row in xts from a data set with its lag. This process should start from the 7th row, which means that the 7th row will be replaced by the 6th row, the 13th row will be replaced by 12th row, and so on.


Solution

  • Here is an easy way using subsetting:

    myxts <- xts::xts(x = 1:100, order.by = seq.Date(from = as.Date("2019-10-17"), by = "d", length.out = 100))
    
    myxts[1:floor(nrow(myxts) / 6) * 6 + 1, ] <- myxts[1:floor(nrow(myxts) / 6) * 6, ] 
    
    2019-10-17    1
    2019-10-18    2
    2019-10-19    3
    2019-10-20    4
    2019-10-21    5
    2019-10-22    6
    2019-10-23    6
    2019-10-24    8
    2019-10-25    9
    2019-10-26   10
    2019-10-27   11
    2019-10-28   12
    2019-10-29   12
    2019-10-30   14
    2019-10-31   15