Tarak Tarak - 1 month ago 16
R Question

R - error expecting a single value using dplyr mutate and if_else

I have a data frame
str is

'data.frame': 334 obs. of 6 variables:
$ Patient_ID : int 524451 517060 518025 515768 499994
$ Camp_Start_Date : Date, format: "2003-08-16" "2005-02-15" "2005-02-15" ...
$ Camp_End_Date : Date, format: "2003-08-20" "2005-02-18" "2005-02-18" ...
$ First_Interaction: Date, format: "2003-08-16" "2004-10-03" "2005-02-17" ...


I am using this to create a new column pRegDate

RegDatelogicLUT <- RegDatelogicLUT %>%
mutate(pRegDate = if_else(between(First_Interaction, Camp_Start_Date, Camp_End_Date), First_Interaction, Camp_Start_Date)
)


Getting the error.

Error: expecting a single value


Any help will be appreciated.
Thanks

J_F J_F
Answer

There is a nice lubridatesolution for this problem:

library(lubridate)

RegDatelogicLUT <- RegDatelogicLUT %>%
  mutate(pRegDate = if_else(First_Interaction %within% c(Camp_Start_Date %--% Camp_End_Date), 
                        First_Interaction, Camp_Start_Date))

#  Patient_ID Camp_Start_Date Camp_End_Date First_Interaction   pRegDate
#1     524451      2003-08-16    2003-08-20        2003-08-16 2003-08-16
#2     517060      2005-02-15    2005-02-18        2004-10-03 2005-02-15
#3     518025      2005-02-15    2005-02-18        2005-02-17 2005-02-17