【问题标题】:3-month and 12-month Moving Average by Customer in RR 中客户的 3 个月和 12 个月移动平均线
【发布时间】:2013-09-03 13:56:05
【问题描述】:

对 R 相当陌生,有一个问题:移动平均/滚动平均

我在 R 中有一个如下所示的表格:

CustomerID | ProductID | FiscalPeriod | Volume  | GP
ABC123        987654     January 2013   $10,000  $3,000
ABC123        987654     February 2013  $500     $200   
ABC123        987654     March 2013     $6,000   $2,000
XYZ555        123456     January 2013   $550     $150
XYZ555        123456     February 2013  $4,000   $800
...

每个客户/产品组合都有一个 FiscalPeriod Volume/GP 值(即使它为零)。

最终,我想要一个如下所示的输出:

CustomerID | ProductID | 3MthMovAvgVol| 12MthMovAvgVol| 3MthMovAvgGP | 12MthMovAvgGP
ABC123       987654      $7,500         $8,250          $1,750         $1,950
XYZ555       123456      $3,500         $4,650          $600           $800

目标是按客户和产品组合为数量和 GP 提供 3m/12m 移动平均/滚动平均值。

我一直在查看 zoo 和 ttr,但似乎无法了解如何执行此操作。

有什么想法吗?

【问题讨论】:

  • 如果您的输出不包含日期,您如何获得移动平均线? IE。您的 3MthMovAvgVol 专栏距离 何时 有 3 个月?
  • 输出列将来自最近完成的时期。例如,如果我今天运行此程序,则输出将在 8 月营业结束时。
  • 那么这不是移动平均线。它只是数据集中最后 X 个周期的平均值。
  • 谢谢,很有意义(回复:第 12 个月)。那么,我将如何创建一个输出,例如上面仅包含前 12 个月的平均值以及按 CustomerID/ProductID 分组的 3MthMovAvg 的输出?

标签: r


【解决方案1】:
## You can use odbc package.For example, you put data in d:/test.xls.
install.packages('RODBC')
library('RODBC')
channel=odbcConnectExcel("d:/test.xls")
## I do not know what 3-months moving average means, you can set conditions using "where" in this SQL below
sqlQuery(channel,'select  a.CustomerID,a.avgVol_12, a.avgGP_12 , b.AvgVol_3 ,b.AvgGP_3   from 
(select CustomerID,sum(Volume)/12 as  avgVol_12,sum(GP)/12 as avgGP_12 from [Sheet1$] group by CustomerID) a  
left outer  join  
(select CustomerID,sum(Volume)/3 as AvgVol_3, sum(GP)/3 as AvgGP_3  from [Sheet1$] where month(FiscalPeriod)>=3 group by CustomerID ) b  
on a.CustomerID=b.CustomerID  ' )

【讨论】:

  • 当您可以简单地使用 sqldf 包时,这是很多额外的工作和潜在的错误。
  • 谢谢 Josh...那么 sqldf 路线会是您推荐我探索的方法吗?
猜你喜欢
  • 1970-01-01
  • 2016-07-07
  • 2013-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
  • 2019-12-16
  • 1970-01-01
相关资源
最近更新 更多