Average between dates based on dates in another dataset using R

I have two data frames: Conc and Flow.

Flow has a value for each day for a given period, while Conc has only a specific value on certain days for a period of a period.

What I want to do is to calculate the average flow rates for each period between Conc values ​​using r.

The following code generates two sample data to illustrate the types of data sets that I work with:

Conc <- data.frame(Date = as.Date(c("2012/01/13", "2012/02/16", "2012/05/02", "2012/07/28",
        "2012/11/10")), Conc = c(0.88, 0.55, 0.34, 0.21, 0.98))
Flow <- data.frame(Date = c(seq(as.Date("2012/01/01"), by = "day", length.out = 365)), 
        Flow = c(sample(seq(from = 0.01, to = 5, by = 0.1), size = 365, replace = TRUE)))

The original data frame should ideally look something like this:

Period    Mean_Flow
1         2.01
2         1.41
3         3.81
4         0.31

, Conc days . , , - Excel, R, , 10 , .

.

+4
2

data.table package foverlaps:

library(data.table)
Conc <- setDT(Conc)[, `:=`(start = Date, end = c(Date[2:(.N - 1)] - 1, Date[.N], NA))][-.N]
Flow <- setDT(Flow)[, `:=`(start = Date, end = Date)]

Flow foverlaps

setkey(Flow, start, end)
overlaps <- foverlaps(Conc, Flow, type = "any", which = TRUE)

Flow

Flow[overlaps$yid, Period := overlaps$xid]
na.omit(Flow[, list(Mean_Flow = mean(Flow)), by = Period])
#    Period Mean_Flow
# 1:      1  2.189412
# 2:      2  2.263947
# 3:      3  2.762874
# 4:      4  2.349048
+5

, Conc $Date. Conc $Date - , A. p , . NaN, .

A <- Conc$Date

for(i in 1:length(A))
{p <- which(Flow$Date>A[i] & Flow$Date<A[i+1])
M<-mean(Flow$Flow[p])
print(M)}
0

All Articles