[R] Putting R script in a function.

Adams, Jean jvadams at usgs.gov
Tue Oct 28 18:09:57 CET 2014


Frederic,

You can simplify your code somewhat using vectorization and the cumsum()
function instead of a for loop.  Since you focus in on a single year,
perhaps you could do the calculations for all the years, and store the
result in an array, instead.  Then you could grab any day*month matrix from
that array as needed.

For example, I created a fake data set and ran the following bit of code ...

Jean


# Fake data
Samsmall <- data.frame(Year=sample(1930:1933, 20, TRUE), Month=rep(1:2,
10),
     Day=sample(20), Rain=sample(20))

Samsmall$Evaporation <- 5
Samsmall$Water_Balance <- cumsum(Samsmall$Rain - Samsmall$Evaporation)
Samsmall$Water_Balance[Samsmall$Water_Balance < 0] <- 0
Samsmall$Water_Balance[Samsmall$Water_Balance > 100] <- 100
Samsmall$Mon <- factor(Samsmall$Month, 1:12, month.abb)

tapply(Samsmall$Water_Balance, list(Samsmall$Day, Samsmall$Mon,
Samsmall$Year), mean)


On Tue, Oct 28, 2014 at 7:40 AM, Frederic Ntirenganya <ntfredo at gmail.com>
wrote:

> 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 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.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list