這裏有一些解決方案:
1)rollapply使用rollapply
和x
和month
這樣的相關程序:
library(zoo)
transform(df, moving_x = rollmean(x, 3, fill = NA),
month_window = rollapply(month, 3, paste, collapse = "-", fill = NA))
給:
Date x month moving_x month_window
1 2000-01-01 0.37963948 Jan NA <NA>
2 2000-02-01 -0.50232345 Feb -0.1519638 Jan-Feb-Mar
3 2000-03-01 -0.33320738 Mar -0.6180354 Feb-Mar-Apr
4 2000-04-01 -1.01857538 Apr -0.8078580 Mar-Apr-May
5 2000-05-01 -1.07179123 May -0.5956127 Apr-May-Jun
6 2000-06-01 0.30352864 Jun -0.1066843 May-Jun-Jul
7 2000-07-01 0.44820978 Jul 0.2682475 Jun-Jul-Aug
8 2000-08-01 0.05300423 Aug 0.4744938 Jul-Aug-Sep
9 2000-09-01 0.92226747 Sep 1.0084521 Aug-Sep-Oct
10 2000-10-01 2.05008469 Oct 0.8271070 Sep-Oct-Nov
11 2000-11-01 -0.49103117 Nov -0.2500385 Oct-Nov-Dec
12 2000-12-01 -2.30916888 Dec NA <NA>
2)b ASE沒有包會更加複雜,但您可以在一個功能,roll3
隱藏複雜性的增加,如圖所示:
roll3 <- function(x, FUN, ...) {
if (length(x) < 3) {
rep(NA, length(x))
} else c(NA, apply(embed(x, 3)[, 3:1], 1, FUN, ...), NA)
}
transform(df, moving_x = roll3(x, mean),
month_window = roll3(as.character(month), paste, collapse = "-"))
,並提供:
Date x month moving_x month_window
1 2000-01-01 0.37963948 Jan NA <NA>
2 2000-02-01 -0.50232345 Feb -0.1519638 Jan-Feb-Mar
3 2000-03-01 -0.33320738 Mar -0.6180354 Feb-Mar-Apr
4 2000-04-01 -1.01857538 Apr -0.8078580 Mar-Apr-May
5 2000-05-01 -1.07179123 May -0.5956127 Apr-May-Jun
6 2000-06-01 0.30352864 Jun -0.1066843 May-Jun-Jul
7 2000-07-01 0.44820978 Jul 0.2682475 Jun-Jul-Aug
8 2000-08-01 0.05300423 Aug 0.4744938 Jul-Aug-Sep
9 2000-09-01 0.92226747 Sep 1.0084521 Aug-Sep-Oct
10 2000-10-01 2.05008469 Oct 0.8271070 Sep-Oct-Nov
11 2000-11-01 -0.49103117 Nov -0.2500385 Oct-Nov-Dec
12 2000-12-01 -2.30916888 Dec NA <NA>
另外請注意,這個問題本身使用包。這個月可以這樣獲得:
df$month <- format(df$Date, "%b")
這是一個了不起的解決方案,我將這個文件提交給未來的應用程序。但是,如果可能的話,我沒有提及(現在糾正)我需要一個基本的R解決方案。 – boshek
已添加基礎解決方案。 –