R: Retrieve the date when a sum is reached

Viewed 23

and thanks in advance!!

I have a climatic dataframe with julian days (DOY), also a start value (TR_EM). For each start date there is a temperature sum (DC55) to be reached by adding the value of each daily value (TMED). I want to iterate over each date to know at what date the DC55 is reached for each TR_EM.

Example:

Input:

province department YEAR DOY TR_EM TMED DC55
Buenos Aires Adolfo Alsina 1985 1 1/1/1985 21.55 300.00
Buenos Aires Adolfo Alsina 1985 2 1/2/1985 23.105 100.00
Buenos Aires Adolfo Alsina 1985 3 1/3/1985 24.88 500.00
Buenos Aires Adolfo Alsina 1985 4 1/4/1985 23.865 1500.00
Buenos Aires Adolfo Alsina 1985 5 1/5/1985 21.5 1855.00
Buenos Aires Adolfo Alsina 1985 6 1/6/1985 21.855 1688.00

Output for the first two values (the date when the first value reaches the closest to 300 on 1/12/1985, and the second value 100 on January 5):

province department YEAR DOY TR_EM TMED DC55 DATE55
Buenos Aires Adolfo Alsina 1985 1 1/1/1985 21.5 300.00 1/12/1985
Buenos Aires Adolfo Alsina 1985 2 1/2/1985 23.1 100.00 1/5/1985

Any ideas? I tried the following but it returns an error:

res <- sum.csv

res1 = NULL res1 = do.call('rbind',lapply(split(res,res$department,drop = T),function(ro){

ro <- droplevels(ro)

print(unique(ro$department)) res_sub2 = NULL

res3 = NULL res3 = do.call('rbind',lapply(split(sum,sum$province,drop = T),function(ro3){

#ro3 <- NULL
#ro3 <- sum[sum$province =="Buenos Aires",]  
#ro3 <- droplevels(ro3)

tmp3 = ro3 %>% #arrange(DOY) %>%
  filter(DOY >= ro$TR_EM) 

tmp4 = tmp3 %>% 
  group_by(Year) %>%
  mutate(tem = cumsum(TMED)) %>%
  group_by(Year) %>%
  summarise(Province = unique(ro3$province), department = unique(ro3$department), 
            FS = unique(ro$TR_EM), Em = round(mean(Em1,na.rm=TRUE), 0), 
            sdem = round(sd(Em1,na.rm=TRUE), 2), %>%
  as.data.frame()  
res_sub2 = rbind(res_sub2,tmp4)
return(res_sub2)

})) }))

0 Answers
Related