I'm trying to assign a diel period to observations based on the time and the month the observation was made.
I have separate data frames, one containing the month and time of the observation and the other containing the starting and ending times for each diel period for each month.
I've written many iterations of code and the closest I have gotten assigns the diel period for the LAST month for all the data (in this case month 12), regardless of the month when the observation was made. Obviously this results in incorrect diel assignment for the other months!
library(tidyverse)
library(hms)
#csv containing diel period classifications
diel <- read_csv("DielPeriod.csv")
#generate data
month <- sort(as.numeric(rep(c(1:12), times = 3)), decreasing = F)
time <- as_hms(rep(c("08:00:00", "13:00:00", "19:00:00"), times = 12))
data <-data.frame(month, time)
#assign diel period based on month and time
for (i in 1:nrow(data)){
t<-data$month[i]
data$dielperiod <- ifelse(data$time > diel[t, "CT_Start"] & data$time <= diel[t,"Morning_End"], "morning",
ifelse(data$time > diel[t, "Morning_End"] & data$time <= diel[t,"Evening_Start"], "midday",
ifelse(data$time > diel[t, "Evening_Start"] & data$time <= diel[t,"CT_End"], "evening",
NA)))
}
This does accomplish my goal, thank you! However for the sake of keeping my data frames smaller and also to learn more about how indexing works, I would like to know how to accomplish this without joining the data frames as well.