Hi All, I wrote this script to calculate the water balance using the following formula: Water_Balance = Water_Balance yesterday + Rainfall - Evaporation.
The code works well and I want to put into a function. conditions: Water_Balance<0 is equal to 0. Water_Balance>100 is equal to 100. Any idea on how I can make it us a function is welcome. # Adding a new column for water balance to the data frame and evaporation Samsmall$Water_Balance <- NA Samsmall$Evaporation<-5 # initialization Samsmall$Water_Balance[1]=0 # loop for calculating water balance for a given dataset ndays <- nrow(Samsmall) for (iday in 2:ndays) { Samsmall$Water_Balance[iday] <- Samsmall$Water_Balance[iday-1] + Samsmall$Rain[iday] - Samsmall$Evaporation[iday] if (Samsmall$Water_Balance[iday]<0){ Samsmall$Water_Balance[iday]=0 }else if(Samsmall$Water_Balance[iday]>100){ Samsmall$Water_Balance[iday]=100 } } ## Table of water balance for a specific year. require(reshape2) samsmall30<-subset(Samsmall,Year==1930) attach(samsmall30) #produce table with data sam30<-dcast(samsmall30,Day~Month,value.var="Water_Balance") #add column names as months colnames(sam30)[2:13]<-month.abb[1:12] Regards, Frederic. [[alternative HTML version deleted]] ______________________________________________ R-help@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.