How can I add a new column with values from the previous with a unique link?

For example, if the data looks like the following, how do I make it so that each follow up date comes in a new column?

Unique ID Date of Screening Date of 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

In this scenario I would like the dataset to look something like this:

Unique ID Date of Screening Date of Follow up 1 Date of Follow up2 Date of Follow up3
1 10-Sep 12-Sep 15-Sep 20-Sep
2 12-Dec 24-Dec 30-Dec

what code can I use for this?

The package you're looking for is tidyr, part of the 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?

Thank you so much! This was super helpful!!
I'm new to R but I will deffo provide a reproducible example next time.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.