[R] Computing Water Balance using a loop.

MacQueen, Don macqueen1 at llnl.gov
Thu Oct 23 18:17:24 CEST 2014


If I understand the problem correctly, then I’d suggest this:

ndays <- nrow(Wb30)

for (iday in 2:ndays) {

  Wb30$Water_Balance[iday] <- Wb30$Water_Balance[iday-1] +
     Wb30$Rainfall[iday] - Wb30$Evaporation[iday]

  Wb30$Water_Balance[iday] <- min(Wb30$Water_Balance[iday], 100)
  Wb30$Water_Balance[iday] <- max(Wb30$Water_Balance[iday], 0)

}

It may be possible without a loop, but I think a loop is easier to
understand in the current circumstances. And is likely to be fast enough
that it does not matter.

- 
Don MacQueen

Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550
925-423-1062





On 10/23/14, 5:33 AM, "Frederic Ntirenganya" <ntfredo at gmail.com> wrote:

>Dear All,
>
>I want to calculate water balance using the following formula:
>Water balance today = Water balance yesterday + Rainfall - Evaporation
>
>This is a sample of data I am using:
>
>head(Wb30)
>  May Rainfall Evaporation Water_Balance
>1   7        0           5             0
>2   8       10           5            NA
>3   9        0           5            NA
>4  10        0           5            NA
>5  11        2           5            NA
>6  12       23           5            NA
>
>The following is the loop am trying to use but it is not working well.
>
>#Water balance today = Water balance yesterday + Rainfall - Evaporation
>#If Water balance today < 0 then Water balance today = 0
>#If Water balance today > 100 then Water balance today = 100
>wb=c()
>for (w in 1:length(Wb30$Water_Balance)){
>  if(w<0 & w>100){w<-0 & w<-100}
>  #print (w);
> for (i in 1:length(Wb30$Rainfall)){
>    for (j in 1:length(Wb30$Evaporation)){
>    }
>  }
> wb<-Wb30$Water_Balance[w] + Wb30$Rainfall[i+1]-Wb30$Evaporation[j+1]
>}
>wb
>
>Any suggest of what I am missing for it to work correctly is welcome.
>
>
>Regards,
>
>Frederic Ntirenganya
>Maseno University,
>African Maths Initiative,
>Kenya.
>Mobile:(+254)718492836
>Email: fredo at aims.ac.za
>https://sites.google.com/a/aims.ac.za/fredo/
>
>	[[alternative HTML version deleted]]
>
>______________________________________________
>R-help at r-project.org mailing list
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide
>http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list