Skip to content

Instantly share code, notes, and snippets.

@SwampThingPaul
Created January 9, 2022 13:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SwampThingPaul/1631473dc51f43449508a5d361a0db3e to your computer and use it in GitHub Desktop.
Save SwampThingPaul/1631473dc51f43449508a5d361a0db3e to your computer and use it in GitHub Desktop.
## Using as.Date with an arbitrary year you can define each peirod
pre.emg.period=seq(as.Date("2021-03-01"),as.Date("2021-03-20"),"1 days")
emg.period=seq(as.Date("2021-03-21"),as.Date("2021-04-14"),"1 days")
mate.period=seq(as.Date("2021-04-15"),as.Date("2021-05-15"),"1 days")
gest.period=seq(as.Date("2021-05-16"),as.Date("2021-08-23"),"1 days")
post.part.period=seq(as.Date("2021-08-24"),as.Date("2021-10-31"),"1 days")
# fake data
dat=data.frame(Date=seq(as.Date("2019-01-01"),as.Date("2022-12-31"),"1 days"))
dat$Yr=as.numeric(format(dat$Date,'%Y'))
## A nested ifelse statement combined with different periods will delineate your periods
dat$period=with(dat,ifelse(format(Date,"%m-%d")%in%format(pre.emg.period,"%m-%d"),"pre.emergence",
ifelse(format(Date,"%m-%d")%in%format(emg.period,"%m-%d"),"emergence",
ifelse(format(Date,"%m-%d")%in%format(mate.period,"%m-%d"),"mating",
ifelse(format(Date,"%m-%d")%in%format(gest.period,"%m-%d"),"gestation",
ifelse(format(Date,"%m-%d")%in%format(post.part.period,"%m-%d"),"post.partum",NA
))))))
## Sanity check
library(plyr)
ddply(dat,c("Yr","period"),summarise,min.date=min(Date),max.date=max(Date))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment