[R] Summing daily data for each year

Gabor Grothendieck ggrothendieck at gmail.com
Wed Mar 17 14:12:17 CET 2010


Try this.  We read in the data using read.zoo and then aggregate it.
read.zoo assumes Date class unless you indicate otherwise.
Then we compute the year and aggregate over that.

as.numeric(format(time(z), "%Y")) would be an alternate way to compute the year.

Lines <- "1995-04-01 0.002766309
1995-04-02 0.002402973
1995-04-03 0.002254335
1995-04-04 0.002221305
1995-04-05 0.002180017
1995-04-06 0.002031379
1995-04-07 0.001957060
1995-04-08 0.001940545
1995-04-09 0.001924030
1995-04-10 0.001783650"

library(zoo)
# z <- read.zoo("myfile.dat")
z <- read.zoo(textConnection(Lines))
aggregate(z, as.numeric(floor(as.yearmon(time(z)))), sum)

The result of the last statement is (since our test data above only
has one year):

      1995
0.02146160

See ?read.zoo and ?aggregate.zoo in the zoo package and also the three
vignettes (pdf documents) that come with the package.




On Wed, Mar 17, 2010 at 2:20 AM,  <Santosh.Aryal at csiro.au> wrote:
>
> Hello there
>
> I have a DAILY data set (as shown below) with Date and
>  Streamflow from April 1995 to Aug 2006.  I want a yearly sum
> the streamflow value (for each year - first and last
> incomplete year).
>
> Does anyone know how to do this in R?
>
> I have tried everything I could think of, e.g. imported the
> streamflow data as time series using:
>
> flowdata <- ts(ZVo[,2],start = c(1995,4,1), frequency = 7) #
> perhaps frequency = 365 is the better one and tried to
> aggregate using aggregate() without success
>
>>ZVo
>             V1      V2
>  1  1995-04-01 0.002766309
>  2  1995-04-02 0.002402973
>  3  1995-04-03 0.002254335
>  4  1995-04-04 0.002221305
>  5  1995-04-05 0.002180017
>  6  1995-04-06 0.002031379
>  7  1995-04-07 0.001957060
>  8  1995-04-08 0.001940545
>  9  1995-04-09 0.001924030
>  10 1995-04-10 0.001783650
>  .
>  .
>  .
>  4156 2006-08-16 0.02861272
>  4157 2006-08-17 0.03652353
>  4158 2006-08-18 0.05372419
>  4159 2006-08-19 0.05630058
>  4160 2006-08-20 0.06274154
>  4161 2006-08-21 0.06981833
>
>  Many thanks
>
>  Santosh
>
> ______________________________________________
> 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