0

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

r2evans
  • 141,215
  • 6
  • 77
  • 149
  • 3
    provide a reproducible sample data – Onyambu Jul 04 '22 at 12:35
  • Welcome to SO, Emilie1992! Questions on SO (especially in R) do much better if they are reproducible and self-contained. By that I mean including attempted code (please be explicit about non-base packages), sample representative data (perhaps via `dput(head(x))` or building data programmatically (e.g., `data.frame(...)`), possibly stochastically), perhaps actual output (with verbatim errors/warnings) versus intended output. Refs: https://stackoverflow.com/q/5963269, [mcve], and https://stackoverflow.com/tags/r/info. – r2evans Jul 04 '22 at 13:15
  • FYI, the tags [tag:datatable] and [tag:data.table] are not the same. While they may seem like it, I suggest reading the text associated with each by either mouse-hovering over it or clicking on it and reading the text at the top of the ensuing page. I made the switch. In general, Stack's tag-recommendation system is imperfect, it is often necessary to review them. Thanks! – r2evans Jul 04 '22 at 13:17
  • use `my_data[, minimum:=sapply(date, function(x)min(value[between(date, x-7, x)])), by=patientID]` – Onyambu Jul 04 '22 at 13:23
  • Thanks a lot onyambu, this is exactly what I was looking for, it makes the code run considerably faster! – Emilie1992 Jul 06 '22 at 08:10

0 Answers0