[R] extending zoo (or ts) objects

Felix Andrews felix at nfrac.org
Sat Oct 20 10:35:48 CEST 2007


I would like to extend zoo objects for use in a hydrological
application. By that I mean I want to attach various attributes, such
as id numbers, coordinates of the observation location, a units
specification, etc. I might also want to add to the "class" attribute
(inheriting from "zoo") and define some custom methods. I can add
attributes() to a zoo object, but the problem is that when I do
operations on the object, such as window, `[`, lag etc, the attributes
are lost. That makes it awkward to manage.

> foo <- zoo(1:5, order.by=as.Date(1:5))
> attr(foo, "location") <- c(150, -35)

The functions below all return a modified zoo object; test which ones
keep the user-specified attributes:

> attr(foo[1:4], "location")
> attr(window(foo), "location")
> attr(lag(foo), "location")
> attr(na.approx(foo), "location") ## this one keeps attributes
[1] 150 -35
> attr(rollmean(foo, 1), "location")
> attr(aggregate(foo, months, mean), "location")

I notice that many operations on ts objects have the same behaviour
(dropping user-specified attributes). In contrast, subsetting
(indexing) a data.frame keeps them, as I had expected.

Any ideas for how to manage this?


Felix Andrews / 安福立
PhD candidate
Integrated Catchment Assessment and Management Centre
The Fenner School of Environment and Society
The Australian National University (Building 48A), ACT 0200
Beijing Bag, Locked Bag 40, Kingston ACT 2604
3358 543D AAC6 22C2 D336  80D9 360B 72DD 3E4C F5D8

More information about the R-help mailing list