df <- data.frame(Date = c("2000-01-05", "2000-02-03", "2000-03-02", "2000-04-13", "2000-05-11", "2000-06-08", "2000-07-06", "2000-09-14", "2000-10-05", "2000-11-02", "2000-12-14", "2001-02-01", "2001-03-01", "2001-04-11", "2001-05-10", "2001-06-07", "2001-07-05", "2001-08-30", "2001-10-11", "2001-11-08", "2001-12-06", "2002-01-03", "2002-02-07", "2002-03-07", "2002-04-04", "2002-05-02", "2002-06-06", "2002-07-04", "2002-09-12", "2002-10-10"), Fit = c( 1.00000000, -1.00000000, -0.81612680, -0.42769496, 1.00000000, -1.50947974, -0.02154276, -1.47427092, -1.46782501, -1.17309887, -0.70347628, -1.93465483, -3.00667550, -1.55652236, -4.10292471, -1.10159442, -2.64296439, -2.03574462, -1.55986632, -1.73125990, -1.34045640, -2.01864867, -2.51081773, -3.07896217, -3.02724723, -0.76456774, -1.81459657, -2.13093106, -1.91543051, -1.31418467))
Предлагаемое решение с использованием dplyr
и tidyr
:
library(dplyr)
library(tidyr)
df <- df %>%
mutate(Date = as.Date(as.character(Date, "%Y-%m-%d")),
Month = format(Date, "%m"),
Year = format(Date, "%Y")) %>%
complete(Month = formatC(1:12, 1, flag=0), nesting(Year)) %>%
mutate(Date = if_else(is.na(Date), as.Date(paste(Year, Month, "1", sep="-"), "%Y-%m-%d"), Date))%>%
arrange(Date) %>%
select(Date, Fit) %>%
mutate(Fit = if_else(is.na(Fit), lag(Fit), Fit)) %>%
mutate(Fit = if_else(is.na(Fit), lag(Fit), Fit)) # Do this twice as a 'hackish' solution for the last value
Возвращает:
Date Fit
1 2000-01-05 1.00000000
2 2000-02-03 -1.00000000
3 2000-03-02 -0.81612680
4 2000-04-13 -0.42769496
5 2000-05-11 1.00000000
6 2000-06-08 -1.50947974
7 2000-07-06 -0.02154276
8 2000-08-01 -0.02154276
9 2000-09-14 -1.47427092
10 2000-10-05 -1.46782501
11 2000-11-02 -1.17309887
12 2000-12-14 -0.70347628
13 2001-01-01 -0.70347628
14 2001-02-01 -1.93465483
15 2001-03-01 -3.00667550
16 2001-04-11 -1.55652236
17 2001-05-10 -4.10292471
18 2001-06-07 -1.10159442
19 2001-07-05 -2.64296439
20 2001-08-30 -2.03574462
21 2001-09-01 -2.03574462
22 2001-10-11 -1.55986632
23 2001-11-08 -1.73125990
24 2001-12-06 -1.34045640
25 2002-01-03 -2.01864867
26 2002-02-07 -2.51081773
27 2002-03-07 -3.07896217
28 2002-04-04 -3.02724723
29 2002-05-02 -0.76456774
30 2002-06-06 -1.81459657
31 2002-07-04 -2.13093106
32 2002-08-01 -2.13093106
33 2002-09-12 -1.91543051
34 2002-10-10 -1.31418467
35 2002-11-01 -1.31418467
36 2002-12-01 -1.31418467