R:通过计算前一天的平均值去除闰日

R: remove leap day by calculating mean with previous day

我有一个时间序列,以下是其中的一个子集:

structure(list(Date = structure(c(16851, 16852, 16853, 16854, 
16855, 16856, 16857, 16858, 16859, 16860), class = "Date"), BAL = c(4.38212529123126, 
6.2362101768993, 7.58042025123348, 1.28668112319138, 0.394057913904365, 
0.223231297328036, -0.677870337868538, -0.803250821089761, -0.812567723037268, 
-0.586754184659877)), row.names = c(NA, -10L), class = c("tbl_df", 
"tbl", "data.frame"))

为了让每年的天数相同,我需要删除 2 月 29 日。我可以通过以下方式轻松做到这一点:

library(lubridate, dplyr)
filter(x, !(month(Date) == 2 & day(Date) == 29))

但是那样的话我会丢失那天的测量信息。我的想法是用 2 月 28 日和 29 日的平均值替换 2 月 28 日的测量值,但我不知道该怎么做。请注意,我原来的时间序列要长得多,并且包含几年的测量结果。

也许你可以试试下面的基本 R 代码

idx <- with(df,which(format(Date,"%m-%d")=="02-29"))
within(df,BAL <- replace(BAL,idx-1,mean(BAL[idx+(-1:0)])))[-idx,]

这给出了

  Date          BAL
  <date>      <dbl>
1 2016-02-20  4.38
2 2016-02-21  6.24
3 2016-02-22  7.58
4 2016-02-23  1.29
5 2016-02-24  0.394
6 2016-02-25  0.223
7 2016-02-26 -0.678
8 2016-02-27 -0.803
9 2016-02-28 -0.700