How to Filter Follow-Up Data Within ±120 Days of 1 Year from Baseline in R

I am new to R. I am working with a dataset in R where each patient is identified by a unique subjectid. Each patient has a baseline_date and multiple follow-up dates (fu_date). I want to filter follow-up records for each subjectid that fall within ±120 days of exactly 1 year (365 days) from the baseline_date.

After filtering, I need to calculate the total exacerbations (fu_exacerbations) for each patient during this period, making this a new column. How can I implement this in R?

This is the test_data.

Thanks a lot for your time!

I dont know how to go about it.

New contributor

Salman Aslam Chaudhary is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

2

First of let’s look at your data:

The 31.6.2022 must be a mistake because June only has 30 days. It should be the 30.6.2022, right? I don’t know where this data is coming from, but it should be carefully checked if it’s health-related! We can do a basic sanity check on the dates of this column.

We should fill in the missing baseline_dates using the fill function. Only then we can calculate the days from baseline like this days_from_baseline = as.numeric(difftime(fu_date, baseline_date, units = "days"))) and filter the abs-days-number for <= 120 days. Afterward, we summarize fu_exacerbations and finally right join it with the underlying data frame:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>library(tidyverse)
library(dplyr)
library(tidyr)
library(lubridate)
library(stringr)
# read data from csv
setwd(dirname(rstudioapi::getSourceEditorContext()$path))
# read csv in file folder
df <- read.csv("test_data.csv")
# To correct dates like "31.6.22" to "30.6.22":
clean_date <- function(date) {
# Ensure the date is character to avoid errors
date <- as.character(date)
# Extract components of the date
month <- as.numeric(stringr::str_extract(date, "^\d{1,2}"))
day <- as.numeric(stringr::str_extract(date, "(?<=/)\d{1,2}(?=/)"))
year <- as.numeric(stringr::str_extract(date, "\d{4}"))
# Correct invalid days based on the month
day <- dplyr::case_when(
month == 4 & day > 30 ~ 30, # April
month == 6 & day > 30 ~ 30, # June
month == 9 & day > 30 ~ 30, # September
month == 11 & day > 30 ~ 30, # November
month == 2 & day > 28 ~ 28, # February (not handling leap years)
TRUE ~ day
)
return(sprintf("%02d/%02d/%04d", month, day, year))
}
# use the function and then fill
result <- df %>% mutate(
baseline_date = if_else(baseline_date != "", clean_date(baseline_date), NA),
# sanity check dates with clean_date
fu_date = if_else(fu_date != "", clean_date(fu_date), NA)
) %>%
fill(baseline_date) %>%
# Group by patient
group_by(subjectid) %>%
# Calculate days from baseline for each follow-up date
mutate(days_from_baseline = as.numeric(difftime(
as.Date(fu_date, format = "%m/%d/%Y"),
as.Date(baseline_date, format = "%m/%d/%Y"),
units = "days"
))) %>%
# Filter records within ±120 days of 1 year
filter(abs(days_from_baseline - 365) <= 120) %>%
# Sum exacerbations for each patient
summarize(total_exacerbations = sum(fu_exacerbations, na.rm = TRUE)) %>%
# Join back with original data to keep other baseline information if needed
right_join(df %>% select(subjectid, baseline_date) %>% distinct(subjectid),
by = "subjectid")
print(result)
</code>
<code>library(tidyverse) library(dplyr) library(tidyr) library(lubridate) library(stringr) # read data from csv setwd(dirname(rstudioapi::getSourceEditorContext()$path)) # read csv in file folder df <- read.csv("test_data.csv") # To correct dates like "31.6.22" to "30.6.22": clean_date <- function(date) { # Ensure the date is character to avoid errors date <- as.character(date) # Extract components of the date month <- as.numeric(stringr::str_extract(date, "^\d{1,2}")) day <- as.numeric(stringr::str_extract(date, "(?<=/)\d{1,2}(?=/)")) year <- as.numeric(stringr::str_extract(date, "\d{4}")) # Correct invalid days based on the month day <- dplyr::case_when( month == 4 & day > 30 ~ 30, # April month == 6 & day > 30 ~ 30, # June month == 9 & day > 30 ~ 30, # September month == 11 & day > 30 ~ 30, # November month == 2 & day > 28 ~ 28, # February (not handling leap years) TRUE ~ day ) return(sprintf("%02d/%02d/%04d", month, day, year)) } # use the function and then fill result <- df %>% mutate( baseline_date = if_else(baseline_date != "", clean_date(baseline_date), NA), # sanity check dates with clean_date fu_date = if_else(fu_date != "", clean_date(fu_date), NA) ) %>% fill(baseline_date) %>% # Group by patient group_by(subjectid) %>% # Calculate days from baseline for each follow-up date mutate(days_from_baseline = as.numeric(difftime( as.Date(fu_date, format = "%m/%d/%Y"), as.Date(baseline_date, format = "%m/%d/%Y"), units = "days" ))) %>% # Filter records within ±120 days of 1 year filter(abs(days_from_baseline - 365) <= 120) %>% # Sum exacerbations for each patient summarize(total_exacerbations = sum(fu_exacerbations, na.rm = TRUE)) %>% # Join back with original data to keep other baseline information if needed right_join(df %>% select(subjectid, baseline_date) %>% distinct(subjectid), by = "subjectid") print(result) </code>
library(tidyverse)
library(dplyr)
library(tidyr)
library(lubridate)
library(stringr)

# read data from csv
setwd(dirname(rstudioapi::getSourceEditorContext()$path))
# read csv in file folder
df <-  read.csv("test_data.csv")

# To correct dates like "31.6.22" to "30.6.22":
clean_date <- function(date) {
  # Ensure the date is character to avoid errors
  date <- as.character(date)
  # Extract components of the date
  month <- as.numeric(stringr::str_extract(date, "^\d{1,2}"))
  day <- as.numeric(stringr::str_extract(date, "(?<=/)\d{1,2}(?=/)"))
  year <- as.numeric(stringr::str_extract(date, "\d{4}"))
  # Correct invalid days based on the month
  day <- dplyr::case_when(
    month == 4 & day > 30 ~ 30,  # April
    month == 6 & day > 30 ~ 30,  # June
    month == 9 & day > 30 ~ 30,  # September
    month == 11 & day > 30 ~ 30, # November
    month == 2 & day > 28 ~ 28,  # February (not handling leap years)
    TRUE ~ day
  )
  return(sprintf("%02d/%02d/%04d", month, day, year))
}


# use the function and then fill
result <- df %>% mutate(
  baseline_date = if_else(baseline_date != "", clean_date(baseline_date), NA),
  # sanity check dates with clean_date
  fu_date = if_else(fu_date != "", clean_date(fu_date), NA)
) %>%
  fill(baseline_date) %>%
  # Group by patient
  group_by(subjectid) %>%
  # Calculate days from baseline for each follow-up date
  mutate(days_from_baseline = as.numeric(difftime(
    as.Date(fu_date, format = "%m/%d/%Y"),
    as.Date(baseline_date, format = "%m/%d/%Y"),
    units = "days"
  ))) %>%
  # Filter records within ±120 days of 1 year
  filter(abs(days_from_baseline - 365) <= 120) %>%
  # Sum exacerbations for each patient
  summarize(total_exacerbations = sum(fu_exacerbations, na.rm = TRUE)) %>%
  # Join back with original data to keep other baseline information if needed
  right_join(df %>% select(subjectid, baseline_date) %>% distinct(subjectid),
             by = "subjectid")

print(result)

It will look like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code># A tibble: 2 × 3
subjectid total_exacerbations baseline_date
<int> <int> <date>
1 2 4 2022-06-30
2 1 NA 2022-11-14
</code>
<code># A tibble: 2 × 3 subjectid total_exacerbations baseline_date <int> <int> <date> 1 2 4 2022-06-30 2 1 NA 2022-11-14 </code>
# A tibble: 2 × 3
  subjectid total_exacerbations baseline_date
      <int>               <int> <date>       
1         2                   4 2022-06-30   
2         1                  NA 2022-11-14   

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

How to Filter Follow-Up Data Within ±120 Days of 1 Year from Baseline in R

I am new to R. I am working with a dataset in R where each patient is identified by a unique subjectid. Each patient has a baseline_date and multiple follow-up dates (fu_date). I want to filter follow-up records for each subjectid that fall within ±120 days of exactly 1 year (365 days) from the baseline_date.

After filtering, I need to calculate the total exacerbations (fu_exacerbations) for each patient during this period, making this a new column. How can I implement this in R?

This is the test_data.

Thanks a lot for your time!

I dont know how to go about it.

New contributor

Salman Aslam Chaudhary is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

2

First of let’s look at your data:

The 31.6.2022 must be a mistake because June only has 30 days. It should be the 30.6.2022, right? I don’t know where this data is coming from, but it should be carefully checked if it’s health-related! We can do a basic sanity check on the dates of this column.

We should fill in the missing baseline_dates using the fill function. Only then we can calculate the days from baseline like this days_from_baseline = as.numeric(difftime(fu_date, baseline_date, units = "days"))) and filter the abs-days-number for <= 120 days. Afterward, we summarize fu_exacerbations and finally right join it with the underlying data frame:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>library(tidyverse)
library(dplyr)
library(tidyr)
library(lubridate)
library(stringr)
# read data from csv
setwd(dirname(rstudioapi::getSourceEditorContext()$path))
# read csv in file folder
df <- read.csv("test_data.csv")
# To correct dates like "31.6.22" to "30.6.22":
clean_date <- function(date) {
# Ensure the date is character to avoid errors
date <- as.character(date)
# Extract components of the date
month <- as.numeric(stringr::str_extract(date, "^\d{1,2}"))
day <- as.numeric(stringr::str_extract(date, "(?<=/)\d{1,2}(?=/)"))
year <- as.numeric(stringr::str_extract(date, "\d{4}"))
# Correct invalid days based on the month
day <- dplyr::case_when(
month == 4 & day > 30 ~ 30, # April
month == 6 & day > 30 ~ 30, # June
month == 9 & day > 30 ~ 30, # September
month == 11 & day > 30 ~ 30, # November
month == 2 & day > 28 ~ 28, # February (not handling leap years)
TRUE ~ day
)
return(sprintf("%02d/%02d/%04d", month, day, year))
}
# use the function and then fill
result <- df %>% mutate(
baseline_date = if_else(baseline_date != "", clean_date(baseline_date), NA),
# sanity check dates with clean_date
fu_date = if_else(fu_date != "", clean_date(fu_date), NA)
) %>%
fill(baseline_date) %>%
# Group by patient
group_by(subjectid) %>%
# Calculate days from baseline for each follow-up date
mutate(days_from_baseline = as.numeric(difftime(
as.Date(fu_date, format = "%m/%d/%Y"),
as.Date(baseline_date, format = "%m/%d/%Y"),
units = "days"
))) %>%
# Filter records within ±120 days of 1 year
filter(abs(days_from_baseline - 365) <= 120) %>%
# Sum exacerbations for each patient
summarize(total_exacerbations = sum(fu_exacerbations, na.rm = TRUE)) %>%
# Join back with original data to keep other baseline information if needed
right_join(df %>% select(subjectid, baseline_date) %>% distinct(subjectid),
by = "subjectid")
print(result)
</code>
<code>library(tidyverse) library(dplyr) library(tidyr) library(lubridate) library(stringr) # read data from csv setwd(dirname(rstudioapi::getSourceEditorContext()$path)) # read csv in file folder df <- read.csv("test_data.csv") # To correct dates like "31.6.22" to "30.6.22": clean_date <- function(date) { # Ensure the date is character to avoid errors date <- as.character(date) # Extract components of the date month <- as.numeric(stringr::str_extract(date, "^\d{1,2}")) day <- as.numeric(stringr::str_extract(date, "(?<=/)\d{1,2}(?=/)")) year <- as.numeric(stringr::str_extract(date, "\d{4}")) # Correct invalid days based on the month day <- dplyr::case_when( month == 4 & day > 30 ~ 30, # April month == 6 & day > 30 ~ 30, # June month == 9 & day > 30 ~ 30, # September month == 11 & day > 30 ~ 30, # November month == 2 & day > 28 ~ 28, # February (not handling leap years) TRUE ~ day ) return(sprintf("%02d/%02d/%04d", month, day, year)) } # use the function and then fill result <- df %>% mutate( baseline_date = if_else(baseline_date != "", clean_date(baseline_date), NA), # sanity check dates with clean_date fu_date = if_else(fu_date != "", clean_date(fu_date), NA) ) %>% fill(baseline_date) %>% # Group by patient group_by(subjectid) %>% # Calculate days from baseline for each follow-up date mutate(days_from_baseline = as.numeric(difftime( as.Date(fu_date, format = "%m/%d/%Y"), as.Date(baseline_date, format = "%m/%d/%Y"), units = "days" ))) %>% # Filter records within ±120 days of 1 year filter(abs(days_from_baseline - 365) <= 120) %>% # Sum exacerbations for each patient summarize(total_exacerbations = sum(fu_exacerbations, na.rm = TRUE)) %>% # Join back with original data to keep other baseline information if needed right_join(df %>% select(subjectid, baseline_date) %>% distinct(subjectid), by = "subjectid") print(result) </code>
library(tidyverse)
library(dplyr)
library(tidyr)
library(lubridate)
library(stringr)

# read data from csv
setwd(dirname(rstudioapi::getSourceEditorContext()$path))
# read csv in file folder
df <-  read.csv("test_data.csv")

# To correct dates like "31.6.22" to "30.6.22":
clean_date <- function(date) {
  # Ensure the date is character to avoid errors
  date <- as.character(date)
  # Extract components of the date
  month <- as.numeric(stringr::str_extract(date, "^\d{1,2}"))
  day <- as.numeric(stringr::str_extract(date, "(?<=/)\d{1,2}(?=/)"))
  year <- as.numeric(stringr::str_extract(date, "\d{4}"))
  # Correct invalid days based on the month
  day <- dplyr::case_when(
    month == 4 & day > 30 ~ 30,  # April
    month == 6 & day > 30 ~ 30,  # June
    month == 9 & day > 30 ~ 30,  # September
    month == 11 & day > 30 ~ 30, # November
    month == 2 & day > 28 ~ 28,  # February (not handling leap years)
    TRUE ~ day
  )
  return(sprintf("%02d/%02d/%04d", month, day, year))
}


# use the function and then fill
result <- df %>% mutate(
  baseline_date = if_else(baseline_date != "", clean_date(baseline_date), NA),
  # sanity check dates with clean_date
  fu_date = if_else(fu_date != "", clean_date(fu_date), NA)
) %>%
  fill(baseline_date) %>%
  # Group by patient
  group_by(subjectid) %>%
  # Calculate days from baseline for each follow-up date
  mutate(days_from_baseline = as.numeric(difftime(
    as.Date(fu_date, format = "%m/%d/%Y"),
    as.Date(baseline_date, format = "%m/%d/%Y"),
    units = "days"
  ))) %>%
  # Filter records within ±120 days of 1 year
  filter(abs(days_from_baseline - 365) <= 120) %>%
  # Sum exacerbations for each patient
  summarize(total_exacerbations = sum(fu_exacerbations, na.rm = TRUE)) %>%
  # Join back with original data to keep other baseline information if needed
  right_join(df %>% select(subjectid, baseline_date) %>% distinct(subjectid),
             by = "subjectid")

print(result)

It will look like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code># A tibble: 2 × 3
subjectid total_exacerbations baseline_date
<int> <int> <date>
1 2 4 2022-06-30
2 1 NA 2022-11-14
</code>
<code># A tibble: 2 × 3 subjectid total_exacerbations baseline_date <int> <int> <date> 1 2 4 2022-06-30 2 1 NA 2022-11-14 </code>
# A tibble: 2 × 3
  subjectid total_exacerbations baseline_date
      <int>               <int> <date>       
1         2                   4 2022-06-30   
2         1                  NA 2022-11-14   

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật