I have a list of dates, and each date has a value.
This is what my data frame looks like right now. Note that there can be repeats in the date, but the entry in value will also repeat with the same value (i.e. row 2 and 3 have the same date, but the respective values are also the same).
date value
1 2018-02-08 1
2 2018-02-09 2
3 2018-02-09 2
4 2018-02-10 4
... ...
This is what I want my data frame to look like
date value weekavg
1 2018-02-08 1 ...
2 2018-02-09 2 ...
3 2018-02-09 2 ...
4 2018-02-10 4 ...
5 2018-02-11 0 ...
6 2018-02-12 0 ...
7 2018-02-13 0 ...
8 2018-02-14 0 ...
9 2018-02-15 0 1
... ... ...
To clarify, the entry in the ninth row is calculated by finding the dates that occurred before it for a week, so for 2018-02-15 that would be the date range 2018-02-08 to 2018-02-13. Thus, the result is 1 since 1+2+4+0+0+0+0 = 7. How could I do this in R, and then do it for every row?
------ Reproducible example -----
data
lines <- "date value
1 2018-02-08 NA
2 2018-02-08 NA
3 2018-02-09 NA
4 2018-02-10 295
5 2018-02-10 295
6 2018-02-11 329
7 2018-02-12 242
8 2018-02-12 242
9 2018-02-13 317
10 2018-02-14 341
11 2018-02-15 292
12 2018-02-16 363
13 2018-02-17 380
14 2018-02-18 319
15 2018-02-19 307
16 2018-02-20 328
17 2018-02-21 290"
df <- read.table(text = lines)
newDF <- merge(df, transform(unique(df), mean = rollmeanr(value, 7, fill = NA)))
the mean column is just NA's for me.
P.S. Apologies for the image comments, I didn't know. Your help is much appreciated.