使用ifelse和dplyr维护POSIXct时间格式

时间:2017-10-11 06:36:43

标签: r if-statement dplyr lubridate

以下数据包含两个人的观察日期。

    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"), 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", "SurveyID", "SurveyDt"), class = "data.frame")

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

SurveyDt列的格式为POSIXct时间戳。我试图用GenIndID汇总dplyr组中的最长日期。在下面的代码中,我使用dplyr创建了两个新列。对于AAA,当max函数使用<NA>参数时,为什么na.rm = F为第二个人生成?对于BBB,我想总结一下活着的个体的最大值,但得到所有NA值(被认为是一个因子,而不是<NA>,这是首选的)。

dat %>% group_by(GenIndID) %>%
  mutate(AAA =  max(SurveyDt, na.rm = FALSE),
         BBB =  ifelse(Fate == "Alive", max(SurveyDt, na.rm = F), NA)) %>%
  as.data.frame()

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

1 个答案:

答案 0 :(得分:1)

我们试试这个

dat %>% group_by(GenIndID) %>%
  mutate(AAA =  max(SurveyDt, na.rm=T),
         BBB =  as.POSIXct(ifelse(Fate == "Alive", max(SurveyDt, na.rm=T), NA), origin='1970-01-01', na.rm=T)) %>%
  as.data.frame()


希望这有帮助!