I need to calculate 2 week percent change for a dataset that may not have samples spaced exactly 14 days apart. This forloop gives me % change for days that are exactly 14 days apart, but can't handle the sampling frequency wobble. I.e. 2022-06-14 % change is NA because there was no sample 2022-05-31 but there is one 2022-05-30. I would like a % change based either on the value of 2022-05-30 or an imputation of 2022-05-31 based on 2022-05-30 and 2022-06-02.
library(dplyr)
library(tidyr)
library(lubridate)
dat.N1 <- structure(list(date = c("2022-04-27", "2022-04-29", "2022-05-02",
"2022-05-04", "2022-05-06", "2022-05-17", "2022-05-19", "2022-05-24",
"2022-05-26", "2022-05-30", "2022-06-02", "2022-06-07", "2022-06-09",
"2022-06-14", "2022-06-17", "2022-06-21", "2022-06-28", "2022-06-30",
"2022-07-05", "2022-07-07", "2022-07-12"), copies_liter = c(168649.864,
62449.256, 464682.88, 127620.624, 2110.27168, 20384.6968, 6817.724,
145.2679712, 0.3792992, 51.4470568, 0.01, 30094.404, 42225.784,
37688.632, 30730.0368, 8108.9016, 6142.6856, 7411.6464, 77131.912,
23668.7056, 11973.198)), row.names = 210:230, class = "data.frame")
dat.N1$date <- as.Date(dat.N1$date)
dat.N1$date_min2 <- dat.N1$date-14
dat.N1$prop <-1:21
for (i in 1:21){
copies_d_current <- dat.N1[i, "copies_liter"]
copies_d_past <- dat.N1[dat.N1[, "date"]==dat.N1[i, "date_min2"],
"copies_liter"]
dat.N1$prop[i] <- ifelse(length(copies_d_current/copies_d_past)==0,
NA,
copies_d_current/copies_d_past %>% as.numeric())
dat.N1$perc <- 100-dat.N1$prop*100
#print(i)
}