0
votes

I need your help please.

My function have to take Tmin and Tmax, then calculates gdd=(Tmin+Tmax)/2 and cumgdd=cumsum(gdd) for each day (row). if cummgdd<=356 , then Tmin<0 = 0 & Tmax>21 = 21 if cumgdd >395 , then Tmin<0 = 0 & Tmax<35 =35.

Please Find Below My Code. It does only apply the first condition, so all Tmax>21 are equal 21.

Many Thanks in Advance.

C.A.

library(dplyr)

climdata= data_frame(j=seq(1,365,by=1), Tmin=runif(min=-3,max=18,n=365),Tmax=runif(min=10,max=39, n=365)

gddcal <- function(climdata,Tmin,Tmax){
  gdd=(Tmin+Tmax)/2
  cumgdd=cumsum(gdd)
  if(cumgdd<=365){
    climdata%>%mutate(tmin=ifelse(Tmin<0,0,Tmin),
                      tmax=ifelse(Tmax>21,21,Tmax),
                      gdd=(tmin+tmax)/2,
                      cumgdd=cumsum(gdd)) -> climdata1
  }else{
    climdata%>%
      filter(cumgdd>395)%>%
      mutate(tmin=ifelse(Tmin<0,0,Tmin),
                      tmax=ifelse(Tmax>35,35,Tmax),
                      gdd=(tmin+tmax)/2,
                      cumgdd=cumsum(gdd))%>%
      bind_rows(climdata1) <- climdata1
  }
  return(climdata1)
} 


1

1 Answers

0
votes

in your code, when you change the if condition you also rewrite the previously defined variables (+ some tiny syntax mistakes). This is what I propose, but column names have to be formatted exactly as your test data.frame

format_climdata <- function(climdata){
  climdata1 <- climdata %>% 
    mutate(gdd=(Tmin+Tmax)/2) %>% 
    mutate(cumgdd=cumsum(gdd))

  climdata2 <-climdata1 %>% 
    mutate(tmin = ifelse(cumgdd > 365 & Tmin < 0, 0, Tmin),
           tmax = ifelse(cumgdd > 365 & Tmax > 35, 35, Tmax)) %>% 
    mutate(tmin = ifelse(cumgdd <= 365 & Tmin < 0, 0, tmin),
           tmax = ifelse(cumgdd <= 365 & Tmax > 21, 21, tmax))

  return(climdata2)
}