[R] Annual cumulative sums from time series

Roger Bivand Roger.Bivand at nhh.no
Thu Feb 10 12:02:58 CET 2005


On Thu, 10 Feb 2005, Georg Hoermann wrote:

> Hello world,
> 
> I am actually transferring a course in data management for
> students in biology, geography and agriculture 
> from statistica to R - it works
> surprisingly well. If anyone is interested in my scratch/notepad
> (in German language), please see
> 
> www.hydrology.uni-kiel.de/~schorsch/statistik/statistik_datenauswertung.pdf
> 
> (pages 40-52)
> 
> The dataset is:
> 
> www.hydrology.uni-kiel.de/~schorsch/statistik/erle_stat.csv
> 
> It contains a 10 year dataset. So far for introduction, now
> comes the problem:
> 
> we often need cumulative *annual* sums (sunshine, precipitation),
>  i.e. the sum
> must reset to 0 at the beginning of the year. I know
> of cumsum(), but I do not now how to split the dataset automagically 
> into annual pieces so I can cumsum() every year separately.
> I have the strong hope that the solution is one of these
> one-liners which leave the students with eyes wide open in surprise and 
> makes them true believers in the power of the command-line 8-).
> 

> kiel <- read.csv(url("http://www.hydrology.uni-kiel.de/~schorsch/statistik/erle_stat.csv"))
> yrs <- factor(strftime(strptime(as.character(kiel$DATUM), "%d.%m.%Y"), 
+ "%Y")) # this is clumsy, there are probably better ways
> tpks1 <- unlist(tapply(kiel$Sonnen, yrs, cumsum))
> str(tpks1)
 Named num [1:3652] 0.12 0.24 0.24 0.24 5.52 ...
 - attr(*, "names")= chr [1:3652] "19891" "19892" "19893" "19894" ...
> kiel$Sonnen[1:5]
[1] 0.12 0.12 0.00 0.00 5.28

I don't know if you want the name attribute on your annual cumulative 
sums, but for now they help control what's going on. This looks OK:

> try1 <- tapply(kiel$Sonnen, yrs, cumsum)
> cols <- rainbow(length(try1))
> plot(x=c(1,366), y=c(0,1200), type="n")
> for (i in 1:length(try1)) lines(1:length(try1[[i]]), try1[[i]], 
+ col=cols[i])
> legend(c(0,70), c(700,1100), names(try1), col=cols, lwd=1)

for a quick impression.


> Thanks & Greetings
> Georg
> 
> 
> 

-- 
Roger Bivand
Economic Geography Section, Department of Economics, Norwegian School of
Economics and Business Administration, Breiviksveien 40, N-5045 Bergen,
Norway. voice: +47 55 95 93 55; fax +47 55 95 93 93
e-mail: Roger.Bivand at nhh.no




More information about the R-help mailing list