简体   繁体   中英

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.

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

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),]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM