Why apply() returns a transposed xts matrix?

时光毁灭记忆、已成空白 提交于 2019-11-26 21:02:48

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!