Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

dplyr

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

like image 436
Tarak Avatar asked Jan 06 '23 04:01

Tarak


1 Answers

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
like image 109
J_F Avatar answered Jan 13 '23 10:01

J_F