I would like to pivot following tibble1 to make tibble2.
tibble1
tibble::tribble(
~SUBJID, ~ARM, ~TIMEPOINT, ~TP.DATE, ~TPR_ar,
2610003, "B", "BL0", "2019-03-26", "Undefined",
2610003, "B", "FU1", "2019-05-30", "SD",
2610003, "B", "FU2", "2019-08-05", "SD",
2610003, "B", "FU3", "2019-10-04", "SD",
2610003, "B", "FU4", "2019-12-04", "NE",
2610003, "B", "FU5", "2020-02-07", "SD",
2610003, "B", "FU6", "2020-04-14", "SD",
2610003, "B", "FU7", "2020-07-07", "SD",
2610004, "C", "BL0", "2019-03-26", "Undefined",
2610004, "C", "FU1", "2019-06-11", "SD",
2610004, "C", "FU2", "2019-07-29", "NE",
2610004, "C", "FU3", "2019-08-20", "PD"
)
tibble2
tibble::tribble(
~SUBJID, ~ARM, ~BL0, ~FU1, ~FU2, ~FU3, ~FU4, ~FU5, ~FU6, ~FU7,
2610003L, "B", "03/26/2019", "05/30/2019", "08/05/2019", "10/04/2019", "12/04/2019", "02/07/2020", "04/14/2020", "07/07/2020",
2610003L, "B", "Undefined", "SD", "SD", "SD", "NE", "SD", "SD", "SD",
2610004L, "C", "03/26/2019", "06/11/2019", "07/29/2019", "08/20/2019", NA, NA, NA, NA,
2610003L, "C", "Undefined", "SD", "NE", "PD", NA, NA, NA, NA
)
So far, I've tried
df %>%
pivot_wider(names_from = c('TIMEPOINT'), values_from = c('TP.DATE','TPR_ar'))
But I didn't get the result I wanted. Your help would be appreciated. Thank you!
CodePudding user response:
First, you need to make TP.DATE
and TPR_ar
into one single variable, then you can pivot by TIMEPOINT
, using them as the variable to fill the values.
library(tidyr)
library(dplyr)
tibble1 %>%
pivot_longer(cols = starts_with("TP")) %>%
select.list(-name) %>%
pivot_wider(names_from = TIMEPOINT,values_from = value)