How does one compute the mean of weekly data by column using R?

纵饮孤独 提交于 2020-02-23 06:33:05

问题


I have a data frame of daily data: df with four columns: Date, A, B, C and am trying to get the mean of weekly data by column. I tried:

library(xts)
xdf <- xts(df[ ,-1],as.Date(df$Date))

apply.weekly(xdf,mean)

but this gives me the mean of all the columns. I need the weekly means of each column.

Thank you for your help


回答1:


First get some data (I'll use a data.frame since that's what you're using, but I really suggest you use a time series class for time series objects)

getSymbols("SPY", src='yahoo', from='2012-05-01', to='2012-06-15',
           return.class='data.frame')
#"SPY"

apply.weekly will split the data up by weeks and apply a function to each week. apply.weekly(SPY, mean) would calculate the mean of all the data for that week, but you want it to calculate the mean of each column for each week. So, you have to apply mean to each column

apply.weekly(SPY, function(x) apply(x, 2, mean))
#           SPY.Open SPY.High SPY.Low SPY.Close SPY.Volume SPY.Adjusted
#2012-05-04 139.6425 140.4675 138.750  139.3275  149400050     138.6075
#2012-05-11 135.9480 136.9320 135.338  136.2040  173105700     135.5020
#2012-05-18 133.3000 133.9180 132.036  132.1760  229282720     131.4960
#2012-05-25 131.7660 132.6800 130.896  132.2140  176634780     131.5340
#2012-06-01 131.7100 132.8925 130.290  131.2725  191170200     130.5950
#2012-06-08 130.2780 131.3380 129.584  130.8580  175917220     130.1820
#2012-06-15 132.8420 133.7760 131.828  132.8020  184751180     132.2540

For reference, apply.weekly is a wrapper for period.apply so you could also get the above result with

period.apply(SPY, endpoints(SPY, "weeks"), FUN=function(x) apply(x, 2, mean))


来源:https://stackoverflow.com/questions/11129562/how-does-one-compute-the-mean-of-weekly-data-by-column-using-r

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