2017-04-20 72 views
0
Date  Sales 
3/11/2017 1 
3/12/2017 0 
3/13/2017 40 
3/14/2017 47 
3/15/2017 83 
3/16/2017 62 
3/17/2017 13 
3/18/2017 58 
3/19/2017 27 
3/20/2017 17 
3/21/2017 71 
3/22/2017 76 
3/23/2017 8 
3/24/2017 13 
3/25/2017 97 
3/26/2017 58 
3/27/2017 80 
3/28/2017 77 
3/29/2017 31 
3/30/2017 78 
3/31/2017 0 
4/1/2017 40 
4/2/2017 58 
4/3/2017 32 
4/4/2017 31 
4/5/2017 90 
4/6/2017 35 
4/7/2017 88 
4/8/2017 16 
4/9/2017 72 
4/10/2017 39 
4/11/2017 8 
4/12/2017 88 
4/13/2017 93 
4/14/2017 57 
4/15/2017 23 
4/16/2017 15 
4/17/2017 6 
4/18/2017 91 
4/19/2017 87 
4/20/2017 44 

这里当前日期为20/04/2017,我的问题是从19/04/2017到2017/03/03的数据分组数据与4个相同的部分与总和销售在r编程?如何将销售数据从昨天开始日期4天分组到r?

如:

library("xts") 
ep <- endpoints(data, on = 'days', k = 4) 
period.apply(data,ep,sum) 

它不工作。然而,它的开始日期是截至目前的日期,但我需要从yestderday(19/4/2017)开始日期的数据并分成4个相等的部分。

好心人任何人指导我很快。

谢谢

回答

0

基础R具有功能cut.Date()这是为特定目的建造的。

但是,问题并不完全清楚OP的意图。我的Q中提供的和额外的comment要求的理解是:

  1. 以每天销售数据Book1但把当天,即,使用只完成了天。
  2. 将数据分组在四个相等的部分中,即包含相同天数的四个周期。 (请注意,Q和使用xts::endpoint()k = 4尝试的标题指示该OP可能有不同的意图组在四天长度每个。周期中的数据)
  3. 总结由周期
  4. 的销售数字

为了简洁起见,data.table在这里用于数据操纵和聚集,lubridate为日期操作

library(data.table) 
library(lubridate) 

# coerce to data.table, convert Date column from character to class Date, 
# exclude the actual date 
temp <- setDT(Book1)[, Date := mdy(Book1$Date)][Date != today()] 

# cut the date range in four parts 
temp[, start_date_of_period := cut.Date(Date, 4)] 

temp 
#   Date Sales start_date_of_period 
# 1: 2017-03-11  1   2017-03-11 
# 2: 2017-03-12  0   2017-03-11 
# 3: 2017-03-13 40   2017-03-11 
# ... 
#38: 2017-04-17  6   2017-04-10 
#39: 2017-04-18 91   2017-04-10 
#40: 2017-04-19 87   2017-04-10 
#   Date Sales start_date_of_period 

# aggregate sales by period 
temp[, .(n_days = .N, total_sales = sum(Sales)), by = start_date_of_period] 
# start_date_of_period n_days total_sales 
#1:   2017-03-11  10   348 
#2:   2017-03-21  10   589 
#3:   2017-03-31  10   462 
#4:   2017-04-10  10   507 

由于,这可以放在一起在一个声明中没有使用一个临时变量:如果要复制的结果在未来

setDT(Book1)[, Date := mdy(Book1$Date)][Date != today()][ 
    , start_date_of_period := cut.Date(Date, 4)][ 
    , .(n_days = .N, total_sales = sum(Sales)), by = start_date_of_period] 

注意,你将不得不调用替换对today()不包括当前日期为mdy("4/20/2017"),这是OP提供的样本数据集中的最后一天。