0

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)))
Mark
  • 7,785
  • 2
  • 14
  • 34
  • Hi martin1104! Welcome to StackOverflow! – Mark Jul 20 '23 at 00:45
  • What does the data in `meas` correspond to? It seems like it has no practical purpose – Mark Jul 20 '23 at 00:45
  • Hi Mark! meas contains a df with three columns indicating: plot id, the initial measurement date and final measurement date of a given period of interest. I want to add a column in this df containing the sum of monthly precipitations (depicted on the precip df). – martin1104 Jul 20 '23 at 02:32

1 Answers1

0

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
Mark
  • 7,785
  • 2
  • 14
  • 34
  • Thanks Mark, when I ran your code im getting the following error: Error in `filter()`: ! Problem while computing `..1 = between(date_met, ini_date, fin_date)`. Caused by error in `between()`: ! `left` must be length 1 – martin1104 Jul 27 '23 at 18:30
  • @martin1104 can you run `dput(meas)` and `dput(precip)` and add it to your question? – Mark Jul 28 '23 at 01:46