如何在R中按月重新采样?

时间:2019-01-04 17:53:31

标签: r

我正试图找到一种方法来按月在r中对时间序列数据进行重新采样。

这可以使用Python中的数据帧重采样来完成。有没有办法可以在R中做同样的事情?

初始数据帧

     Date       Qty
05/25/2018       10
08/20/2018       15
10/15/2018       25

应更改为

    Date        Qty
03/01/2018       0
04/01/2018       0
05/01/2018       10
06/01/2018       0
07/01/2018       0
08/01/2018       15
09/01/2018       0
10/01/2018       25
11/01/2018       0
12/01/2018       0

2 个答案:

答案 0 :(得分:1)

data.tablelubridate方法

library( data.table )
library( lubridate )

dt <- fread("Date       Qty
05/25/2018       10
08/20/2018       15
10/15/2018       25", header = TRUE)

#create data.table with first day of each month
dt.months <- data.table( Date = seq( as.Date("2018-01-01"), length=12, by="1 month"))

#set Date as actual date, and floor to the first day of the month
dt[, Date := floor_date( as.Date( Date, format = "%m/%d/%Y"), "month" )]
#sum qty by month (noft needed in this example)

#left join
result <- dt[dt.months, on = "Date", nomatch = NA ]
#replace NA with 0
result[is.na(result)] <- 0

result
Date Qty
# 1: 2018-01-01   0
# 2: 2018-02-01   0
# 3: 2018-03-01   0
# 4: 2018-04-01   0
# 5: 2018-05-01  10
# 6: 2018-06-01   0
# 7: 2018-07-01   0
# 8: 2018-08-01  15
# 9: 2018-09-01   0
# 10: 2018-10-01  25
# 11: 2018-11-01   0
# 12: 2018-12-01   0

答案 1 :(得分:0)

我敢肯定有一种更快的方法,但是可以。

    LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL
        IDD_LOGIN DIALOG 0, 0, 186, 95
        STYLE DS_3DLOOK | DS_CENTER | DS_MODALFRAME | DS_SHELLFONT | WS_CAPTION |
        WS_VISIBLE | WS_POPUP | WS_SYSMENU
        CAPTION "Dialog"
        FONT 8, "Ms Shell Dlg"
    {
        LTEXT           "Enter Password", 0, 52, 19, 75, 9, SS_LEFT, WS_EX_LEFT
        EDITTEXT        IDD_EDIT, 34, 33, 113, 17, ES_AUTOHSCROLL, WS_EX_LEFT
        PUSHBUTTON      "Cancel", IDCANCEL, 30, 65, 50, 14, 0, WS_EX_LEFT
        DEFPUSHBUTTON   "OK", IDOK, 106, 65, 50, 14, 0, WS_EX_LEFT
    }