Filter data in R based on condition?

Viewed 39

I want to filter the dataframe below, to where only certain rows are kept.

Rows should be kept if the medication is ordered either 30 minutes BEFORE the start time of surgery, or during the surgery (which is determined by TotalORTime). If a medication was not issued during a surgery (or within 30min before the start of the procedure), it should be excluded.

total.Date = date of surgery

total.PTIN = start time of surgery

total.TotalORTime = duration of surgery (minutes)

total.ISSUE_DATE = date of medication ordered

total.ISSUE_TIME = time of medication ordered

> dput(ty)
structure(list(total.Date = c("8/11/2022", "8/2/2022", "8/16/2022", 
"7/15/2022", "6/30/2022"), total.PTIN = c("10:59:59", "14:41:00", 
"11:20:54", "10:34:59", "13:16:00"), total.TotalORTime = c(55L, 
73L, 47L, 210L, 15L), total.ISSUE_DATE = c("06/29/2022", "07/12/2022", 
"08/05/2022", "06/11/2022", "07/10/2022"), total.ISSUE_TIME = c("06:47:00", 
"05:28:00", "12:27:00", "06:26:00", "14:26:00")), row.names = c(27204L, 
25631L, 35339L, 12779L, 28237L), class = "data.frame")

In this specific subsetted dataset, I believe all rows will be excluded. However when I perform this on the entire dataset, some rows are expected to remain.

1 Answers

First pasting together the surgery and order dates and times to form proper datetimes, then converting the integer minutes into a "period" object in lubridate terminology.

Then it's straightforward to filter: greater than the start time minus 30 minutes AND less than the start time plus the length of the surgery.

library(dplyr)
library(lubridate)

your_df %>%
  mutate(
    surgery_start = mdy_hms(paste(total.Date, total.PTIN)),
    order_time = mdy_hms(paste(total.ISSUE_DATE, total.ISSUE_TIME)),
    surgery_duration = minutes(total.TotalORTime)
    ) %>%
  filter(
    order_time > surgery_start - minutes(30),
    order_time < surgery_start + surgery_duration
  )
Related