为什么apply()返回一个转置的XTmatrix?

我想运行一个xtsmatrix的所有时期的函数。 apply()非常快,但返回的matrix与原始对象相比具有转置的维度:

> 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维度?

这就是apply被logging下来的事情。 来自?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)的数组c(48, 7429)

另外请注意, myxts.2 不是一个xts对象。 这是一个普通的数组。 你有几个select:

  1. 在重新创build您的xts对象之前调换应用的结果:

     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. 向量化你的函数,使它对一个xts对象的所有行进行操作并返回一个xts对象。 那么你根本不用担心apply

最后,请开始提供可重复的例子。 这并不难,让人们更容易帮忙。 我已经提供了一个上面的例子,我希望你可以在你的下面的问题中使用它。