Cumulate precipitations over measurement periods by groups

40 Views Asked by At

I am trying to cumulate monthly precipitations by plot measurement dates. Plots were measured at uneven dates and have their own rain records on a separate df.

dfs:

precip=as.data.frame(cbind(id=c(1,1,1,1), date_met=c('2021-01-01', '2021-02-01', '2021-03-01', '2021-04-01'), precip=c(20, 23, 23, 23)))
precip=precip %>% mutate(precip=as.numeric(precip), date_met=ymd(date_met))

meas=as.data.frame(cbind(id=c(1,1,2), ini_date=c('2021-01-01', '2022-02-02', '2021-02-03'), fin_date=c('2022-02-02','2023-04-03','2022-02-03')))
meas=meas %>% mutate(ini_date=ymd(ini_date), fin_date=ymd(fin_date))

So far, I have been able to do the cumulation not considering the plot id which is not right.
Any helps is appreciated.

require(cropgrowdays)
yield <- meas|> 
    dplyr::mutate(swd= purrr::map2_dbl(ini_date, fin_date, function(x, y)
        cumulative(precip, var = precip, startdate = x, enddate = y)))
1

There are 1 best solutions below

2
On

I think this is what you want:

left_join(meas, precip, by="id", relationship = "many-to-many") %>%
    filter(between(date_met, ini_date, fin_date)) %>%
    summarise(precip=sum(precip), .by = c("id", "ini_date", "fin_date")) %>%
    right_join(meas) %>%
    replace_na(list(precip=0))

  id   ini_date   fin_date precip
1  1 2021-01-01 2022-02-02     89
2  1 2022-02-02 2023-04-03      0
3  2 2021-02-03 2022-02-03      0