[R] Sum of some months totals

Adams, Jean jvadams at usgs.gov
Tue Apr 14 12:52:23 CEST 2015


If you want to calculate the number of days having greater than a certain
threshold of rain within a range of months, a function like this might
serve your needs.

raindays <- function(data, monStart=1, monEnd=3, threshold=0.85) {
  with(data, {
    selRows <- Month >= monStart & Month <= monEnd & Rain > threshold
    days <- tapply(selRows, Year, sum)
    return(days)
  })
}

raindays(kitale)

Jean

On Tue, Apr 14, 2015 at 2:46 AM, Frederic Ntirenganya <ntfredo at gmail.com>
wrote:

> I want to compute monthly summaries from daily data. I want to choose which
> month to start and how many months to total over.  Default could be to
> start in January and total over 3 months.  For the number of rain days the
> default threshold is 0.85mm.
>
> I tried to make a function which sum all months not some of months. I will
> appreciate any help from you guys. Thanks.
> Here is the data and the code I used.
>
> > dput(head(kitale))structure(list(Year = c(1979L, 1979L, 1979L, 1979L,
> 1979L, 1979L
> ), Month = c(1L, 1L, 1L, 1L, 1L, 1L), Day = 1:6, Rain = c(0,
> 0, 0, 0, 0, 0)), .Names = c("Year", "Month", "Day", "Rain"), row.names =
> c(NA,
> 6L), class = "data.frame")
>
> here is the function:
>
> total = function(data, threshold = 0.85){
>   month_tot=matrix(NA,31,12)
>   rownames(month_tot)=as.character(1979:2009)
>
> colnames(month_tot)=c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
>   raindays=month_tot
>   # loop over months and years to get summary statistics
>   for (mon in 1:12) {
>     rain=data[data[2]==mon,c(1,4)]   # rain just for a specific month
>     for (yr in 1979:2009) {
>       month_tot[yr-1978,mon]=sum(rain[rain[,1]==yr,2])
>       raindays[yr-1978,mon]=sum(rain[rain[,1]==yr,2]>threshold)
>     }
>   }
>   month_tot
> }
>
> Regards,
>
> Frederic.
>
>
>
> 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 -- To UNSUBSCRIBE and more, see
> 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