Home > database >  R : calculating date with reference
R : calculating date with reference

Time:01-12

stackoverflow R users! I have following tribble.

tibble::tribble(
  ~SUBJID, ~ARM, ~TIMEPOINT,     ~TP.DATE,     ~TPR_ar,     ~TPR_ir,
  1,  "A",      "BL0", "2020-05-13", "Undefined", "Undefined",
  1,  "A",      "FU1", "2020-08-04",        "SD",        "SD",
  1,  "A",      "FU2", "2020-10-06",        "PR",        "PR",
  1,  "A",      "FU3", "2020-12-10",        "PR",        "PR",
  )

Now, I would like to get :

tibble::tribble(
  ~SUBJID, ~ARM, ~TIMEPOINT,     ~TP.DATE,     ~TPR_ar,     ~TPR_ir, ~Dref
  1,  "A",      "BL0", "2020-05-13", "Undefined", "Undefined","0",
  1,  "A",      "FU1", "2020-08-04",        "SD",        "SD","83",
  1,  "A",      "FU2", "2020-10-06",        "PR",        "PR","146"
  )

That is, 2020-08-04 is 83 days from 2020-05-13, 2020-10-06 is 146 days from 2020-05-13

How can I achieve this? thank you very much!

CodePudding user response:

Here a tidyverse approach

Data

data <-
tibble::tribble(
  ~SUBJID, ~ARM, ~TIMEPOINT,     ~TP.DATE,     ~TPR_ar,     ~TPR_ir,
  1,  "A",      "BL0", "2020-05-13", "Undefined", "Undefined",
  1,  "A",      "FU1", "2020-08-04",        "SD",        "SD",
  1,  "A",      "FU2", "2020-10-06",        "PR",        "PR",
  1,  "A",      "FU3", "2020-12-10",        "PR",        "PR",
)

Code

library(dplyr)
library(lubridate)

data %>% 
  mutate(TP.DATE = ymd(TP.DATE)) %>% 
  mutate(Dref = as.numeric(TP.DATE - min(TP.DATE)))

Output

# A tibble: 4 x 7
  SUBJID ARM   TIMEPOINT TP.DATE    TPR_ar    TPR_ir     Dref
   <dbl> <chr> <chr>     <date>     <chr>     <chr>     <dbl>
1      1 A     BL0       2020-05-13 Undefined Undefined     0
2      1 A     FU1       2020-08-04 SD        SD           83
3      1 A     FU2       2020-10-06 PR        PR          146
4      1 A     FU3       2020-12-10 PR        PR          211
  • Related