mercredi 11 octobre 2017

Nested condtionals in dplyr ifelse statement

I am using dplyr and ifelse to create a new column based on two conditionals with the data below.

dat <- structure(list(GenIndID = c("BHS_034", "BHS_034", "BHS_068", 
"BHS_068", "BHS_068", "BHS_068", "BHS_068", "BHS_068", "BHS_068", 
"BHS_068", "BHS_068"), IndID = c("BHS_034_A", "BHS_034_A", "BHS_068_A", 
"BHS_068_A", "BHS_068_A", "BHS_068_A", "BHS_068_A", "BHS_068_A", 
"BHS_068_A", "BHS_068_A", "BHS_068_A"), Fate = c("Mort", "Mort", 
"Alive", "Alive", "Alive", "Alive", "Alive", "Alive", "Alive", 
"Alive", "Alive"), Status = c("Alive", "Mort", "Alive", "Alive", 
"MIA", "Alive", "MIA", "Alive", "MIA", "Alive", "Alive"), Type = c("Linked", 
"Linked", "SOB", "SOB", "SOB", "SOB", "SOB", "SOB", "SOB", "SOB", 
"SOB"), SurveyID = c("GYA13-1", "GYA14-1", "GYA13-1", "GYA14-1", 
"GYA14-2", "GYA15-1", "GYA16-1", "GYA16-2", "GYA17-1", "GYA17-3", 
"GYA15-2"), SurveyDt = structure(c(1379570400, 1407477600, 1379570400, 
1407477600, 1409896800, NA, 1462946400, 1474351200, 1495519200, 
1507010400, 1441951200), tzone = "", class = c("POSIXct", "POSIXt"
))), row.names = c(NA, 11L), .Names = c("GenIndID", "IndID", 
"Fate", "Status", "Type", "SurveyID", "SurveyDt"), class = "data.frame")

> dat
   GenIndID     IndID  Fate Status   Type SurveyID   SurveyDt
1   BHS_034 BHS_034_A  Mort  Alive Linked  GYA13-1 2013-09-19
2   BHS_034 BHS_034_A  Mort   Mort Linked  GYA14-1 2014-08-08
3   BHS_068 BHS_068_A Alive  Alive    SOB  GYA13-1 2013-09-19
4   BHS_068 BHS_068_A Alive  Alive    SOB  GYA14-1 2014-08-08
5   BHS_068 BHS_068_A Alive    MIA    SOB  GYA14-2 2014-09-05
6   BHS_068 BHS_068_A Alive  Alive    SOB  GYA15-1       <NA>
7   BHS_068 BHS_068_A Alive    MIA    SOB  GYA16-1 2016-05-11
8   BHS_068 BHS_068_A Alive  Alive    SOB  GYA16-2 2016-09-20
9   BHS_068 BHS_068_A Alive    MIA    SOB  GYA17-1 2017-05-23
10  BHS_068 BHS_068_A Alive  Alive    SOB  GYA17-3 2017-10-03
11  BHS_068 BHS_068_A Alive  Alive    SOB  GYA15-2 2015-09-11

More specifically, grouping by GenIndID I want to make a new date field that is the max SurveyDt based on a two conditionals for Type and Fate. Additionally, I want the max date to only evaluate SurveyDt when Status == Alive. My code below produces all NA values, rather than the described date field for BHS_068 which meets all of the specified conditionals.

I recently saw case_when which may be appropriate here, but I could not implement it correctly.

dat %>% group_by(GenIndID) %>%
  mutate(NewDat = as.POSIXct(ifelse(Type == "SOB" & Fate == "Alive", max(SurveyDt[Status == "Alive"], na.rm = F), NA), 
                             origin='1970-01-01', na.rm=T)) %>%
  as.data.frame()

Any suggestions would be appreciated.

Aucun commentaire:

Enregistrer un commentaire