The package you're looking for is tidyr
, part of the tidyverse
.
library(tidyverse)
dat = tribble(
~id, ~screening, ~follow_up,
1, "10-Sep", "12-Sep",
1, "10-Sep", "15-Sep",
1, "10-Sep", "20-Sep",
2, "12-Dec", "24-Dec",
2, "12-Dec", "30-Dec"
) |>
mutate(screening = lubridate::dmy(paste(screening, "2020")),
follow_up = lubridate::dmy(paste(follow_up, "2020")))
dat_wide = dat |>
group_by(id) |>
mutate(n_fu = paste0("follow_up_", row_number())) |>
pivot_wider(names_from = n_fu,
values_from = follow_up)
> dat_wide
# A tibble: 2 x 5
# Groups: id [2]
id screening follow_up_1 follow_up_2 follow_up_3
<dbl> <date> <date> <date> <date>
1 1 2020-09-10 2020-09-12 2020-09-15 2020-09-20
2 2 2020-12-12 2020-12-24 2020-12-30 NA
Next time you post, it is useful to provide your data as a reproducible example to make it easier to access on our computers:
FAQ: What's a reproducible example (reprex
) and how do I create one?