日期不匹配,因此针对示例进行了更改。通过这种方法,您可以准确检查比赛的进行情况并确保其符合您的要求。
df1<-data.frame(Datetime=c("2016-08-18 15:34:07","2016-08-18 16:25:16","2016-08-18 17:29:16","2016-08-18 18:33:16","2016-08-18 20:54:16","2016-08-18 22:48:16"),Site=c("BD","HG","BD","BD","BD","BD"),Ind=c(16,17,19,16,17,16), Depth=c(5.3,24,36.4,42,NA,22.1))
df1$Datetime<-as.POSIXct(df1$Datetime, format="%Y-%m-%d %H:%M:%S",tz="UTC")
df2<-data.frame(Datetime=c("2016-08-18 12:00:00","2016-08-18 15:00:00","2016-08-18 18:00:00","2016-08-18 21:00:00","2016-08-19 00:00:00"), Site=c("BD","BD","BD","BD","BD"),var1=c(2.75,4,6.75,2.25,4.3),var2=c(3,4,4.75,3,2.1),var3=c(2.75,4,5.75,2.25,1.4),var4=c(3.25,3,6.5,2.75,3.4),var5=c(3,4,4.75,3,1.7))
df2$Datetime<-as.POSIXct(df2$Datetime, format="%Y-%m-%d %H:%M:%S",tz="UTC")
colnames(df2)<-c("Datetime","Site","m0-7","m8-15","m16-23","m24-31","m32-39")
library(dplyr)
library(lubridate)
# Round the date and convert the depth to match the look-up.
df1 = df1 %>%
mutate(
Datetime_rounded = round_date(Datetime, "3 hour"),
Depth_ind = ifelse(Depth < 8, "m0-7",
ifelse(Depth > 7 & Depth < 16, "m8-15",
ifelse(Depth > 15 & Depth < 24, "m16-23",
ifelse(Depth > 23 & Depth < 32, "m24-31",
ifelse(Depth > 31 & Depth < 40, "m32-39", NA)
)
)
)
)
)
# Wide to long on the intensity columns.
df2 = df2 %>%
tidyr::gather("Depth_ind", "Intensity", 3:7)
# Join
df1 %>%
left_join(df2, by = c("Datetime_rounded" = "Datetime",
"Site",
"Depth_ind"))
Datetime Site Ind Depth Datetime_rounded Depth_ind Intensity
1 2016-08-18 15:34:07 BD 16 5.3 2016-08-18 15:00:00 m0-7 4.00
2 2016-08-18 16:25:16 HG 17 24.0 2016-08-18 15:00:00 m24-31 NA
3 2016-08-18 17:29:16 BD 19 36.4 2016-08-18 18:00:00 m32-39 4.75
4 2016-08-18 18:33:16 BD 16 42.0 2016-08-18 18:00:00 <NA> NA
5 2016-08-18 20:54:16 BD 17 NA 2016-08-18 21:00:00 <NA> NA
6 2016-08-18 22:48:16 BD 16 22.1 2016-08-19 00:00:00 m16-23 1.40
# EDIT ----
## As per the request, the width of the final depth range can be adjusted as you wish, e.g. to a max depth of 60 m.
# Round the date and convert the depth to match the look-up.
df1 = df1 %>%
mutate(
Datetime_rounded = round_date(Datetime, "3 hour"),
Depth_ind = ifelse(Depth < 8, "m0-7",
ifelse(Depth > 7 & Depth < 16, "m8-15",
ifelse(Depth > 15 & Depth < 24, "m16-23",
ifelse(Depth > 23 & Depth < 32, "m24-31",
ifelse(Depth > 31 & Depth < 60, "m32-39", NA)
)
)
)
)
)