为什么 apply() 返回一个转置的 xts 矩阵? [英] Why apply() returns a transposed xts matrix?

查看:22
本文介绍了为什么 apply() 返回一个转置的 xts 矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 xts 矩阵的所有周期上运行一个函数.apply() 非常快,但与原始对象相比,返回的矩阵具有转置维度:

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:

> dim(myxts)
[1] 7429   48
> myxts.2 = apply(myxts, 1 , function(x) { return(x) })
> dim(myxts.2)
[1]   48 7429
> str(myxts)
An 'xts' object from 2012-01-03 09:30:00 to 2012-01-30 16:00:00 containing:
  Data: num [1:7429, 1:48] 4092500 4098500 4091500 4090300 4095200 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:48] "Open" "High" "Low" "Close" ...
  Indexed by objects of class: [POSIXlt,POSIXt] TZ: 
  xts Attributes:  
 NULL
> str(myxts.2)
 num [1:48, 1:7429] 4092500 4098500 4091100 4098500 0 ...
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:48] "Open" "High" "Low" "Close" ...
  ..$ : chr [1:7429] "2012-01-03 09:30:00" "2012-01-03 09:31:00" "2012-01-03 09:32:00" "2012-01-03 09:33:00" ...
> nrow(myxts)
[1] 7429
> head(myxts)
                       Open    High     Low   Close
2012-01-03 09:30:00 4092500 4098500 4091100 4098500
2012-01-03 09:31:00 4098500 4099500 4092000 4092000
2012-01-03 09:32:00 4091500 4095000 4090000 4090200 
2012-01-03 09:33:00 4090300 4096400 4090300 4094900
2012-01-03 09:34:00 4095200 4100000 4095200 4099900
2012-01-03 09:35:00 4100000 4100000 4096500 4097500 

如何保留 myxts 尺寸?

How can I preserve myxts dimensions?

推荐答案

这就是 apply 记录的目的.从 ?apply:

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

值:

 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’.

在您的情况下,'n'=48(因为您正在遍历行),所以 apply 将返回一个维度为 c(48, 7429).

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

另请注意,myxts.2 不是一个 xts 对象.这是一个常规数组.您有几个选择:

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

  1. 在重新创建 xts 对象之前转置 apply 的结果:

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

  • 矢量化您的函数,使其对 xts 的所有行进行操作对象并返回一个 xts 对象.那你就不用担心了关于apply.

    最后,请开始提供可重现的示例.这并不难,它使人们更容易提供帮助.我在上面提供了一个示例,希望您可以在以下问题中使用它.

    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.

    这篇关于为什么 apply() 返回一个转置的 xts 矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆