问题描述
我有一个每日数据的数据框:df,有四列:Date, A, B, C
并试图按列获取每周数据的平均值.我试过了:
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.
感谢您的帮助
推荐答案
首先获取一些数据(我将使用 data.frame
因为这是您正在使用的,但我真的建议您对时间序列对象使用时间序列类)
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
将按周拆分数据并对每周应用一个函数.apply.weekly(SPY, mean)
将计算该周所有数据的平均值,但您希望它计算每周 每列的平均值.所以,你必须apply
mean
到每一列
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
作为参考,apply.weekly
是 period.apply
的包装器,因此您也可以使用
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))
这篇关于如何使用 R 按列计算每周数据的平均值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!