jeetkamal
jeetkamal

Reputation: 409

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.

Upvotes: 0

Views: 40

Answers (2)

IceCreamToucan
IceCreamToucan

Reputation: 28675

The code below will subtract 1 from the index if the index is 1 after a multiple of 6. So 7 will become index 6, 13 will become 12, etc. Subsetting your xts object with this new index will give the result you describe

i <- seq(nrow(myxts))
myxts[i - (i %% 6L == 1L),]

Upvotes: 1

Cettt
Cettt

Reputation: 11981

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

Upvotes: 1

Related Questions