我正在尝试模拟研究参与者的访问时间表。我将从参与者和首次访问日期的数据框开始,我的目标是创建包含后续访问日期的列。
参与者将在第一次访问后定期进行研究访问。间隔取决于研究组。我已将这些间隔存储在向量中。
我想最终得到一个数据框,其中每一行都是参与者,并且每个访问次数都有日期列。我可以使用 case_when 来完成此操作,但我有很多次访问和手臂(未在 reprex 中显示)。该示例的输出工作正常,但我正在寻找更强大且更简洁的解决方案。
library(dplyr)
# set up schedules
arm1 <- c(0, 14, 28)
arm2 <- c(0, 14, 19, 180)
arm3 <- c(0, 14, 28, 32)
# simulate dataframe for 30 participants
d0 <- data.frame(
ids = seq(1:30),
studyarm = rep(c("arm1", "arm2", "arm3"), 10),
date_visit1 = rep(seq(as.Date("2024-06-01"), as.Date("2024-06-10"), by = 1)))
# add visit dates depending on arm
d1 <- d0 %>%
mutate(
date_visit2 = case_when(
studyarm == "arm1" ~ date_visit1 + arm1[2],
studyarm == "arm2" ~ date_visit1 + arm2[2],
studyarm == "arm3" ~ date_visit1 + arm3[2]
),
date_visit3 = case_when(
studyarm == "arm1" ~ date_visit1 + arm1[3],
studyarm == "arm2" ~ date_visit1 + arm2[3],
studyarm == "arm3" ~ date_visit1 + arm3[3]
),
date_visit4 = case_when(
studyarm == "arm1" ~ date_visit1 + arm1[4], # correctly returns NA
studyarm == "arm2" ~ date_visit1 + arm2[4],
studyarm == "arm3" ~ date_visit1 + arm3[4]
)
)
一个选项是将手臂收集到一个框架中,间隔列命名为
date_visit2 ... 4
,然后可以通过 d0
将其连接到 studyarm
,并且所有间隔都可以通过单个 mutate(across(...))
调用转换为日期。
library(dplyr)
# set up schedules
arms <- tribble(
~arm, ~date_visit2, ~date_visit3, ~date_visit4,
"arm1", 14, 28, NA,
"arm2", 14, 19, 180,
"arm3", 14, 28, 32
)
# simulate dataframe for 30 participants
d0 <- data.frame(
ids = seq(1:30),
studyarm = rep(c("arm1", "arm2", "arm3"), 10),
date_visit1 = rep(seq(as.Date("2024-06-01"), as.Date("2024-06-10"), by = 1)))
d0 %>%
left_join(arms, by = join_by(studyarm == arm)) %>%
mutate(across(date_visit2:date_visit4, ~date_visit1 + .x)) %>%
as_tibble()
#> # A tibble: 30 × 6
#> ids studyarm date_visit1 date_visit2 date_visit3 date_visit4
#> <int> <chr> <date> <date> <date> <date>
#> 1 1 arm1 2024-06-01 2024-06-15 2024-06-29 NA
#> 2 2 arm2 2024-06-02 2024-06-16 2024-06-21 2024-11-29
#> 3 3 arm3 2024-06-03 2024-06-17 2024-07-01 2024-07-05
#> 4 4 arm1 2024-06-04 2024-06-18 2024-07-02 NA
#> 5 5 arm2 2024-06-05 2024-06-19 2024-06-24 2024-12-02
#> 6 6 arm3 2024-06-06 2024-06-20 2024-07-04 2024-07-08
#> 7 7 arm1 2024-06-07 2024-06-21 2024-07-05 NA
#> 8 8 arm2 2024-06-08 2024-06-22 2024-06-27 2024-12-05
#> 9 9 arm3 2024-06-09 2024-06-23 2024-07-07 2024-07-11
#> 10 10 arm1 2024-06-10 2024-06-24 2024-07-08 NA
#> # ℹ 20 more rows
创建于 2024-05-03,使用 reprex v2.1.0