I have a dataset with 3 columns: patient ID, a numeric value of a lab test, and the date the lab test was performed. I want to compute the rolling minimum value per row within a window of 7 days. The question has already been asked and the following code was given:
library(dplyr)
df %>%
mutate(
minimum = sapply(date, function(x) min(value[between(date, x - 7, x)]))
)
This works great but it is not efficient enough for my huge dataset. I am trying to convert this code using data.table but can't make it work. This is what I have done:
f<-function(x) min(value[between(date, x - 7, x)])
my_data[, lapply(.SD, f), .SDcols=c("value","date"), on=patientID]
What is wrong with my code, please? Thanks a lot for your help