根据重复遭遇添加新的日期字段

时间:2018-01-03 01:59:41

标签: r dplyr lubridate

我重复遇到具有唯一IndIDII和唯一GPSSrl号码的动物。每次遭遇都有一个FstCptr日期。

dat <- structure(list(IndIDII = c("BHS_115", "BHS_115", "BHS_372", "BHS_372", 
"BHS_372", "BHS_372"), GPSSrl = c("035665", "036052", "034818", 
"035339", "036030", "036059"), FstCptr = structure(c(1481439600, 
1450162800, 1426831200, 1481439600, 1457766000, 1489215600), class = c("POSIXct", 
"POSIXt"), tzone = "")), .Names = c("IndIDII", "GPSSrl", "FstCptr"
), class = "data.frame", row.names = c(1L, 2L, 29L, 30L, 31L, 
32L))

> dat
   IndIDII GPSSrl    FstCptr
1  BHS_115 035665 2016-12-11
2  BHS_115 036052 2015-12-15
29 BHS_372 034818 2015-03-20
30 BHS_372 035339 2016-12-11
31 BHS_372 036030 2016-03-12
32 BHS_372 036059 2017-03-11

对于每个IndID-GPSSrl分组,我想创建一个新字段(NextCptr),用于记录下次遇到的日期。对于最后一次遇到,新字段将为NA,例如:

dat$NextCptr <- as.Date(c("2015-12-15", NA, "2016-12-11", "2016-03-12", "2017-03-11", NA))

> dat
   IndIDII GPSSrl    FstCptr   NextCptr
1  BHS_115 035665 2016-12-11 2015-12-15
2  BHS_115 036052 2015-12-15       <NA>
29 BHS_372 034818 2015-03-20 2016-12-11
30 BHS_372 035339 2016-12-11 2016-03-12
31 BHS_372 036030 2016-03-12 2017-03-11
32 BHS_372 036059 2017-03-11       <NA>

我想在dplyrgroup_by(IndIDII, GPSSrl)内工作。

一如既往,非常感谢!

1 个答案:

答案 0 :(得分:1)

按专栏IndIDII进行分组,然后使用leadFstCptr向前移动一个:

dat %>% group_by(IndIDII) %>% mutate(NextCptr = lead(FstCptr))

# A tibble: 6 x 4
# Groups:   IndIDII [2]
#  IndIDII GPSSrl             FstCptr            NextCptr
#    <chr>  <chr>              <dttm>              <dttm>
#1 BHS_115 035665 2016-12-11 02:00:00 2015-12-15 02:00:00
#2 BHS_115 036052 2015-12-15 02:00:00                  NA
#3 BHS_372 034818 2015-03-20 02:00:00 2016-12-11 02:00:00
#4 BHS_372 035339 2016-12-11 02:00:00 2016-03-12 02:00:00
#5 BHS_372 036030 2016-03-12 02:00:00 2017-03-11 02:00:00
#6 BHS_372 036059 2017-03-11 02:00:00                  NA

如果您需要向相反方向移动列,lag也可能有用,dat %>% group_by(IndIDII) %>% mutate(NextCptr = lag(FstCptr))