Apply via xts with multiple columns

I have a strange error that I cannot understand. Let me explain the variables and their meaning:

ts <- a xts object
range.matrix <- matrix with two columns and n rows (only knows at execution time)

therefore range.matrixcontains date ranges. the first column is the beginning of the range, and the second column is its end. The goal is to slice the ts time series with ranges in range.matrix a to get a list with all slices.

It fails with some ranges, but not in others, and does not work with 1 row matrices ... Error message:

An error in the array (ans, c (len.a% /% d2, d.ans) if (! Is.null (names (dn.ans)) the length of "dimnames" 1 is not equal to the size of the array

Check yourself with the example of this toy ( range.matrixcontains numbers that are cast as .Date)

    library(xts)
    ts <- xts(cbind('a'= c(1,2,3,4,5,6,7,8),'b' =c(1,2,3,4,5,6,7,8),'c'= c(1,2,3,4,5,6,7,8))
            ,order.by = as.Date(as.Date('2017-01-01'):(as.Date('2017-01-01')+7)) )

    range.matrix <- matrix(c(16314,17286), ncol = 2,byrow = TRUE) # Fails. Range: "2014-09-01/2017-04-30"
    range.matrix <- matrix(c(16314,17236,16314,17286), ncol = 2,byrow = TRUE) # Fails. Range: "2014-09-01/2017-03-11" and "2014-09-01/2017-04-30"
    range.matrix <- matrix(c(16314,17236,17237,17286), ncol = 2,byrow = TRUE) # does not fail. "2014-09-01/2017-03-11" and "2017-03-12/2017-04-30"

    apply(range.matrix,
          1,
          function(r) {
          ts[paste0(as.Date(r[1]), '/', as.Date(r[2]))]
          })

Any clue? This is due to dimnamesbut cannot find a solution.

+4
1

, :

lapply(split(range.matrix, row(range.matrix)), function(x) {
  ts[paste0(as.Date(r[1]), '/', as.Date(r[2]))]})

apply xts , ( , lapply ).

apply , xts - (), , . - coredata xts, apply, , .

apply(range.matrix,
      1,
      function(r) {
        res <- ts[paste0(as.Date(r[1]), '/', as.Date(r[2]))]
        coredata(res)
      })
+4

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


All Articles