Why apply() returns a transposed xts matrix?

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.

Leave a Comment