R - 使用dplyr mutate和if_else期望单个值的错误

时间:2016-10-21 11:17:54

标签: r dplyr

我有一个数据框 str是

  '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" ...

我用它来创建一个新列pRegDate

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

获取错误。

  Error: expecting a single value

任何帮助将不胜感激。 感谢

1 个答案:

答案 0 :(得分:3)

这个问题有一个很好的lubridate解决方案:

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