'How can I improve my model using Kalman filter in this case?

I'm trying to build a model that predicts humidity W
This is the data I'm working with :

tibble [364 x 6] (S3: tbl_df/tbl/data.frame)
 $ DATE             : POSIXct[1:364], format: "2016-09-01" "2016-09-02" "2016-09-03" ...
 $ Pluie mm par jour: num [1:364] 0 0 0 0 0 0 2 0 0 2 ...
 $ PLUIE+IRR mm/jour: num [1:364] 38.5 0 0 0 0 0 2 0 0 2 ...
 $ Ep mm/jour       : num [1:364] 3.9 3.8 4 4.2 5.4 4.5 2.9 3.5 3.8 4 ...
 $ SWI observé      : num [1:364] 42 41.5 41.5 41.5 43 43.5 44.5 43 42.5 42.5 ...
 $ W_obs            : num [1:364] 154 153 153 153 158 ...

Pluie stands for the amount of rain
Ep stands for the evaporation
Wobs stands for the observed humidity ( the one I'm going to use to calculate the error of estimation ).

The model I used for the estimation is this one :

Ep=df$`Ep mm/jour`
Pr=df$`PLUIE+IRR mm/jour`
Wobs=df$W_obs
  
h=function(W,Ep,Pr,Wmax,s){
  Wmax=as.numeric(Wmax)
  s=as.numeric(s)
  G_d=exp((W-226.9672)/54.44444)-1.063127
  m=min(W/(s*Wmax),1)
  West=W-m*Ep+Pr-G_d
  return(West)
}
f=function(W,h,Ep,Pr,Wmax,s){
  Wmax=Wmax
  s=s
  We=c(W)
  for(i in 1:h){
    w=h(We[i],Ep[i],Pr[i],Wmax=Wmax,s=s)
    We=append(We,w)
  }
  return(We)
}
West=ts(f(0,length(Ep),Ep,Pr,490,0.56))

The initial values of my estimations aren't very good ( the red curve is the estimated humidity ) enter image description here

I want to apply kalman filter to smooth it but I didn't know how to do that in R. Does anyone know how can I use the Kalman filter in this case to improve my model?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source