My data frame consists of individual observations of individual animals. Each animal has a birthdate, that I would like to associate to the closest field season date from a date vector.
Here is a very basic reproducible example:
ID <- c("a", "b", "c", "d", "a") # individual "a" is measured twice here
birthdate <- as.Date(c("2012-06-12", "2014-06-14", "2015-11-11", "2016-09-30", "2012-06-12"))
df <- data.frame(ID, birthdate)
# This is the date vector
season_enddates <- as.Date(c("2011-11-10", "2012-11-28", "2013-11-29", "2014-11-26", "2015-11-16", "2016-11-22", "2012-06-21", "2013-06-23", "2014-06-25", "2015-06-08", "2016-06-14"))
With the following code, I can get the difference between the birthdate and the closest season enddate.
for(i in 1:length(df$birthdate)){
df$birthseason[i] <- which(abs(season_enddates-df$birthdate[i]) == min(abs(season_enddates-df$birthdate[i])))
}
However, what I want is the actual date, and not the difference. For example, the first value of birthseason should be 2012-06-21.
lubridate
package? – Tontineyounger$HatchCalendarYear1
comes from, for example. – Colophon