1

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

Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
adam.888
  • 7,686
  • 17
  • 70
  • 105

1 Answers1

8

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))
GSee
  • 48,880
  • 13
  • 125
  • 145
  • I have problems installing this.I get an error message:install.packages("xts",repos="http://r-forge.r-project.org") Warning message: package ‘xts’ is not available (for R version 2.15.0) – adam.888 Jun 21 '12 at 11:42
  • It turns out that I was getting that output because another package that I had loaded was colliding with xts. So, updating to the dev version of `xts` will not help you. Sorry. I will update the post. – GSee Jun 21 '12 at 22:44
  • 4
    `apply.weekly(SPY, colMeans)` provides the same results and is quite a bit more succinct. – Joshua Ulrich Aug 08 '12 at 14:35