Why apply() returns a transposed xts matrix?

前端 未结 1 1368
青春惊慌失措
青春惊慌失措 2020-11-27 22:35

I want to run a function on all periods of an xts matrix. apply() is very fast but the returned matrix has transposed dimensions compared to the original object:

<         


        
相关标签:
1条回答
  • 2020-11-27 23:36

    That's what apply is documented to do. From ?apply:

    Value:

     If each call to ‘FUN’ returns a vector of length ‘n’, then ‘apply’
     returns an array of dimension ‘c(n, dim(X)[MARGIN])’ if ‘n > 1’.
    

    In your case, 'n'=48 (because you're looping over rows), so apply will return an array of dimension c(48, 7429).

    Also note that myxts.2 is not an xts object. It's a regular array. You have a couple options:

    1. transpose the results of apply before re-creating your xts object:

      data(sample_matrix)
      myxts <- as.xts(sample_matrix)
      dim(myxts)    # [1] 180   4
      myxts.2 <- apply(myxts, 1 , identity)
      dim(myxts.2)  # [1]   4 180
      myxts.2 <- xts(t(apply(myxts, 1 , identity)), index(myxts))
      dim(myxts.2)  # [1] 180   4
      
    2. Vectorize your function so it operates on all the rows of an xts object and returns an xts object. Then you don't have to worry about apply at all.

    Finally, please start providing reproducible examples. It's not that hard and it makes it a lot easier for people to help. I've provided an example above and I hope you can use it in your following questions.

    0 讨论(0)
提交回复
热议问题