0

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.

ulfelder
  • 5,305
  • 1
  • 22
  • 40
jeetkamal
  • 399
  • 2
  • 12

2 Answers2

1

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
Cettt
  • 11,460
  • 7
  • 35
  • 58
  • running this code is giving this error Error in `[.xts`(x, i, which.i = TRUE) : subscript out of bounds – jeetkamal Oct 17 '19 at 12:13
  • can you replicate this example with 192 columns – jeetkamal Oct 17 '19 at 12:32
  • strange. I just tried with a fresh R session and it works perfectly. Can you restart R and try again? If it does not work: which R version are you using? And can you post the output of `sessionInfo()`? – Cettt Oct 17 '19 at 12:34
  • This should also work for multiple columns in the same way it works for one. – Cettt Oct 17 '19 at 12:35
  • ok R version 3.6.0 (2019-04-26) Platform: x86_64-w64-mingw32/x64 (64-bit) Running under: Windows 10 x64 (build 17134) – jeetkamal Oct 17 '19 at 12:45
  • which version of `xts` are you using? – Cettt Oct 17 '19 at 12:47
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/201027/discussion-between-cettt-and-jeetkamal). – Cettt Oct 17 '19 at 12:54
1

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),]
IceCreamToucan
  • 28,083
  • 2
  • 22
  • 38