本文介绍了如何在具有多列的动物园对象中使用`apply.monthly`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 pp 的动物园对象,其中包含每日数据和 77 列,如下所示:

I have a zoo object called pp with daily data and 77 columns that looks like this:

            X02R X03N X04K X04N X04R X06I X06N X08J X08P X09O X11O X12L X14N X15G X16K  (...)
1961-01-01  8.3  5.2  3.2  0.0  8.7  5.2 15.0  7.2 11.5 13.0  0.0  4.9  0.0  2.9  6.0   
1961-01-02  1.1  3.2 10.0  0.0  0.0  3.5  0.0  8.7  0.4  1.2  0.0  0.4  0.0  3.2  0.2    
1961-01-03 12.0  4.2 50.5  0.0  9.0 38.5 15.0 31.7  1.7  8.7  9.0 69.2  4.2 22.2  9.2 
(...)  

我想对每一列使用 apply.monthly,所以最后我仍然有 77 列,但有每月数据而不是每日数据.我试过apply.monthly(pp, FUN=sum) 但结果是一个只有一列的动物园对象(我认为是添加所有列).

I want to use apply.monthly to each of the columns, so in the end I will still have 77 columns but with monthly data instead of daily data. I tried apply.monthly(pp, FUN=sum) but the result is a zoo object with just one column (I think is adding all the columns).

我也尝试了一个循环:

for (i in 1:77){mensal 但它也只产生一列(第 77 列).我也许可以通过一些试验和错误使循环工作,但计算需要很长时间(我有 17897 行和 77 列),我想有一种更简单的方法可以不使用循环来做到这一点......所以如果你知道怎么办,请帮忙.谢谢!

for (i in 1:77){mensal<-apply.monthly(pp[,i], FUN=sum)} but it also results in just one column (the 77th column). I might be able to make the loop work with some trial and error but it takes ages to compute ( I have 17897 rows and 77 columns) and I guess there is a simpler way of doing this without using loops... So if you know how, please help. Thanks!

推荐答案

为了让 apply.monthly 返回一个多列的对象,你必须使用一个按列操作的函数(或应用一个没有的功能).

In order for apply.monthly to return an object with more than one column, you have to use a function that operates by column (or apply a function that doesn't).

library(quantmod)
getSymbols("SPY")
zSPY <- as.zoo(SPY)
# sum doesn't operate by column; it sums everything to one value
sum(zSPY)
spy.sum <- apply.monthly(zSPY, sum)
# colSums operates by column
spy.colSums <- apply.monthly(zSPY, colSums)
# use apply to operate by column
spy.apply.sum <- apply.monthly(zSPY, apply, 2, sum)

这篇关于如何在具有多列的动物园对象中使用`apply.monthly`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 22:25