2017-04-20 36 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提供的樣本數據集中的最後一天。

相關問題