zoo/0000755000175400001440000000000012156677575011301 5ustar zeileisuserszoo/MD50000644000175400001440000001342612156677575011617 0ustar zeileisusers9bffa22f275d735e64299b7667d9bd14 *DESCRIPTION b2a997bbba9e387404297607e70f86a6 *NAMESPACE 5161003ea100f3fb054791368073f56a *NEWS 0d3a237bf61d1881c7ebebd69c3b30c9 *R/MATCH.R 58526e3e16531c683e1b40a3d08c3fc5 *R/ORDER.R edfffc6f33c6eb4f4ff6a35b08e1bfd7 *R/Ops.zoo.R 407a111f9bd9245db5aeb1b999df2499 *R/aggregate.zoo.R 9b2752b85b382ef96a6f28663170491e *R/as.Date.R 93ff2d240541d0aa3588d410eb235699 *R/as.Date.ts.R 117e4d69a8786865fca6ede2b09c6e19 *R/as.zoo.R aa948827212d6c0e3834f6eef7b6e82a *R/as.zoo.tis.R 5413af6851aed20d8fa81a8f7a895737 *R/barplot.zoo.R eb9ae996db706251ae065c6b77877cde *R/coredata.R 122f8b11ee7a4c1e3146b0e227e5f94f *R/ggplot2.zoo.R 2e834ac5e827d8becce70582dc1949aa *R/index.R e0b9e9a919725d282d7b4e608e42a364 *R/index2char.R e9e788521e48a8c3eea367971cb9633e *R/is.regular.R faa14832f6dd3b8e4920e3dea63834ee *R/merge.zoo.R d3d3379645412d1da0c24bcb49291583 *R/na.StructTS.R 4e8c25337f2e1891e0939ebf2e6b0138 *R/na.aggregate.R 700075b9d6c2a1b0922d138fd5aeb9fa *R/na.approx.R 468b2282a3260ea7b1790e5b047b28e4 *R/na.fill.R dd2e1368324e6b8ee8179d9c4b570123 *R/na.locf.R d912001ad34a995582e851f1b471c0e9 *R/na.spline.R 53f4edd246db8ca0c69567c5fb1dad61 *R/na.trim.R ae059d28cc5c0b7cc3fd6bce24b9bdeb *R/plot.zoo.R d1a70c38b42b9e8a0429c529ec6cbd99 *R/read.zoo.R 37a3a11361580562ea0e830fa4b09958 *R/rollapply.R 80350d05a3bd71276845a1ff9cb890b5 *R/rollmean.R 89e9c21c3558acb9e95dfab063e5c5d5 *R/window.zoo.R 94aa2ade75635c4dee7754036bce16c0 *R/xblocks.R 042ac20be5fd3a3edcc46386568dff77 *R/xyplot.zoo.R 996748cfebb9a620caaf12d451d96912 *R/yearmon.R 479405a1a4bb0f76994d33a20ac1d36c *R/yearqtr.R b9849a3fad4a691d6591fd6fce5da238 *R/zoo.R 3070a310d50f4bfe3d0a11e6e8354dcf *R/zooreg.R 21bede1b02820b648012773b5d3994fe *THANKS bdc15aaa93d42a0e813dbca29806940a *TODO 5501e7a0d36298870a7fc614a70c4941 *WISHLIST beb8720082847566abaa78c65ee97815 *demo/00Index 59d8732e0de2f3cb82141eb8d97a2477 *demo/zoo-overplot.R caf8cbff3ce975a11a2457d4b9b09ef6 *inst/CITATION 965dc0e909a6be66370cdfd3b7732589 *inst/doc/MSFT.rda a916af484ffa11d8aa8669404a25e53c *inst/doc/demo1.txt 5ad2a643bb73c28764fd4db6db457261 *inst/doc/demo2.txt 8ab6ae33767b9f99c8158192e12832c1 *inst/doc/sunw.rda e90680abb6a7cd9bd8de0e07667711b7 *inst/doc/zoo-design.R 5051eb1d34cd0d183e2d84449912c9f8 *inst/doc/zoo-design.Rnw c6bed94f5f2774446c5a35c44da10ed3 *inst/doc/zoo-design.pdf 45323f04a5e08dc2af3187376b1b0d90 *inst/doc/zoo-faq.R 598475df10385cb019bd104c3e23bbca *inst/doc/zoo-faq.Rnw 4bcbf730f89251250e656a358ed4e104 *inst/doc/zoo-faq.pdf 026bf98b7f811d1487b7927b1caf46db *inst/doc/zoo-quickref.R 8ec9c8c8b5a27088b6a4603f05e8822e *inst/doc/zoo-quickref.Rnw 1d347ca75c872e1e1dc2d7ef7e54b964 *inst/doc/zoo-quickref.pdf db43f0f2f8675281720628ff6a8c6e34 *inst/doc/zoo-read.R 8345be10caf2e3f0170b706caf3e2c11 *inst/doc/zoo-read.Rnw 56f7d04927cd6599ec7a7f989924221d *inst/doc/zoo-read.pdf 4efdcb35305f5de95990635041387074 *inst/doc/zoo.R eb337d4629019c86db356af4cbbbeaa5 *inst/doc/zoo.Rnw 69f29233f0590692196f1dd2bd04d1ca *inst/doc/zoo.pdf b9399dea40883cbabe28389558bea5b1 *man/MATCH.Rd ce5614980ae640df7c8388f72de3a0ca *man/ORDER.Rd 7d9d99d22e0e55574b9f982f7690ba7f *man/aggregate.zoo.Rd 1e21be7a4038d4d52308f0f8251dc0e2 *man/as.zoo.Rd d375aef8bdbff49760670062a49606f8 *man/coredata.Rd a91c3b70c28fc5e49376918e6f963781 *man/frequency.Rd b3ad5c179da7752d1a3d0e0061825408 *man/ggplot2.zoo.Rd 8aa5402c809f7cc9c67c4225c37dcd16 *man/index.Rd eb05cdfc731836569c961b0f75033e45 *man/is.regular.Rd c97b5855503b079c6bb4ec2e47764ede *man/lag.zoo.Rd 2a40905ca067abf2ac4b679c6e12748a *man/make.par.list.Rd c74dd08722ed8c81c46a9bd01d84f2c6 *man/merge.zoo.Rd 280a0fa48fe9b99f66956fe4931de5f7 *man/na.StructTS.Rd d2c2255460d224a4a7c332f5c03cce4c *man/na.aggregate.Rd 30058032c107d8a9f811a7b406337181 *man/na.approx.Rd 812e67ad96f11c0b6ac87f1c1d447417 *man/na.fill.Rd b563566d30230fec9c5d1e8fa6e507d0 *man/na.locf.Rd 72f8fedd1165de8c679ebbedc552c04b *man/na.trim.Rd b58440cedf693183602e7c46bf6edee0 *man/plot.zoo.Rd 5bb6af8cd5f7e15346a369decde0130c *man/read.zoo.Rd 94d85c7ca6fa7207c457a39645ca08ef *man/rollapply.Rd dfa01f12f04ca00ec3b70b76e0aba2e8 *man/rollmean.Rd d0cbd403034400d2df9a4d55d38e815e *man/window.zoo.Rd b01d46391c525d1510c69c3bcbe70744 *man/xblocks.Rd eb33e870fccca3e5aac3d1ac198e542b *man/xyplot.zoo.Rd 322fef4da3c5282c24eca48e437260ce *man/yearmon.Rd 5226a5473c1f6dc7a3954f76c62d995a *man/yearqtr.Rd a0ad96b1d8212a88749a5f4e5996defb *man/zoo.Rd 28545accfae55aba893bb6ef4ea51a18 *man/zooreg.Rd aa5bac3353d00be05a9bbabef9696bc8 *src/coredata.c 0292cb3c50739e490289729872c22507 *src/init.c 29d9b7988cf840ee7adb20adfca75a92 *src/lag.c dd2909911733f11d02837283e885402e *src/zoo.h 24fd58574e062f05abb08883344d9b57 *tests/Examples/zoo-Ex.Rout.save b512f313e67b56e595e06e7854eeb49e *tests/as.Date.R 83cce8658b8a1368a6f2ee1a5abe8360 *tests/as.Date.Rout.save 240ad939b84e1d2db4a7fc231d52ab40 *tests/bugfixes.R e68afbb730ccd84d4ba765cb4c521b06 *tests/bugfixes.Rout.save 747601a7627f9f4d3166c1e80812fe75 *tests/vignette-zoo-quickref.R 5ac8f2c5488afcbbc42f1a0eefead099 *tests/vignette-zoo-quickref.Rout.save 720280779ba1db456681dbb28dd74c43 *tests/vignette-zoo.R e365ca0e42f1a9d795dd2430f8425e6f *tests/vignette-zoo.Rout.save 965dc0e909a6be66370cdfd3b7732589 *vignettes/MSFT.rda a916af484ffa11d8aa8669404a25e53c *vignettes/demo1.txt 5ad2a643bb73c28764fd4db6db457261 *vignettes/demo2.txt 8ab6ae33767b9f99c8158192e12832c1 *vignettes/sunw.rda 5051eb1d34cd0d183e2d84449912c9f8 *vignettes/zoo-design.Rnw 598475df10385cb019bd104c3e23bbca *vignettes/zoo-faq.Rnw 8ec9c8c8b5a27088b6a4603f05e8822e *vignettes/zoo-quickref.Rnw 8345be10caf2e3f0170b706caf3e2c11 *vignettes/zoo-read.Rnw 6ad1f9d56475d122f628fd147278c38e *vignettes/zoo-refcard-raw.tex ecc325b9e45907aa10e771f4cd578a2f *vignettes/zoo-refcard.pdf ef7fd243ec57bc81c59c22bad0214916 *vignettes/zoo-refcard.tex eb337d4629019c86db356af4cbbbeaa5 *vignettes/zoo.Rnw 76d25c4dcd6fdf3973e49f0e21c08072 *vignettes/zoo.bib zoo/vignettes/0000755000175400001440000000000012155437504013272 5ustar zeileisuserszoo/vignettes/zoo.bib0000644000175400001440000000703411747047642014571 0ustar zeileisusers@Article{zoo:Zeileis+Grothendieck:2005, author = {Achim Zeileis and Gabor Grothendieck}, title = {\pkg{zoo}: \proglang{S3} Infrastructure for Regular and Irregular Time Series}, journal = {Journal of Statistical Software}, year = 2005, volume = 14, number = 6, pages = {1--27}, url = {http://www.jstatsoft.org/v14/i06/} } @Manual{zoo:R:2008, title = {\proglang{R}: {A} Language and Environment for Statistical Computing}, author = {{\proglang{R} Development Core Team}}, organization = {\proglang{R} Foundation for Statistical Computing}, address = {Vienna, Austria}, year = {2008}, note = {{ISBN} 3-900051-07-0}, url = {http://www.R-project.org/} } @Article{zoo:Zeileis+Leisch+Hornik:2002, author = {Achim Zeileis and Friedrich Leisch and Kurt Hornik and Christian Kleiber}, title = {\pkg{strucchange}: {A}n \proglang{R} Package for Testing for Structural Change in Linear Regression Models}, journal = {Journal of Statistical Software}, year = 2002, volume = 7, number = 2, pages = {1--38}, url = {http://www.jstatsoft.org/v07/i02/} } @Article{AER:Zeileis:2005, author = {Achim Zeileis}, title = {Implementing a Class of Structural Change Tests: An Econometric Computing Approach}, journal = {Computational Statistics \& Data Analysis}, volume = {50}, issue = {11}, pages = {2987--3008}, year = {2006}, doi = {10.1016/j.csda.2005.07.001}, } @Manual{zoo:Rmetrics:2008, title = {\pkg{Rmetrics}: {A}n Environment and Software Collection for Teaching Financial Engineering and Computational Finance}, author = {Diethelm Wuertz}, year = {2010}, note = {\proglang{R}~packages \pkg{fArma}, \pkg{fAsianOptions}, \pkg{fAssets}, \pkg{fBasics}, \pkg{fCalendar}, \pkg{fCopulae}, \pkg{fEcofin}, \pkg{fExoticOptions}, \pkg{fExtremes}, \pkg{fGarch}, \pkg{fImport}, \pkg{fMultivar}, \pkg{fNonlinear}, \pkg{fOptions}, \pkg{fPortfolio}, \pkg{fRegression}, \pkg{fSeries}, \pkg{fTrading}, \pkg{fUnitRoots}, \pkg{fUtilities}}, url = {http://www.Rmetrics.org/}, } @Manual{zoo:tseries:2007, title = {\pkg{tseries}: Time Series Analysis and Computational Finance}, author = {Adrian Trapletti}, year = {2009}, note = {\proglang{R}~package version~0.10-22}, url = {http://CRAN.R-project.org/package=tseries} } @Manual{zoo:its:2004, title = {\pkg{its}: Irregular Time Series}, author = {Giles Heywood}, organization = {Portfolio \& Risk Advisory Group and Commerzbank Securities}, year = {2009}, note = {\proglang{R} package version 1.1.8}, url = {http://CRAN.R-project.org/package=its}, } @Manual{zoo:DAAG:2004, title = {\pkg{DAAG}: Data Analysis and Graphics}, author = {John Maindonald and W. John Braun}, year = {2009}, note = {\proglang{R} package version 1.01}, url = {http://CRAN.R-project.org/package=DAAG}, } @Manual{zoo:xts:2008, title = {\pkg{xts}: Extensible Time Series}, author = {Jeffrey A. Ryan and Josh M. Ulrich}, year = {2010}, note = {\proglang{R} package version 0.7-1}, url = {http://CRAN.R-project.org/package=xts}, } @Manual{zoo:RUnit, title = {\pkg{RUnit}: \proglang{R} Unit Test Framework}, author = {Matthias Burger and Klaus J\"unemann and Thomas K\"onig}, year = {2009}, note = {\proglang{R} package version 0.4.25}, url = {http://CRAN.R-project.org/package=RUnit}, } zoo/vignettes/zoo.Rnw0000644000175400001440000014042111747047642014601 0ustar zeileisusers\documentclass[article,nojss]{jss} \DeclareGraphicsExtensions{.pdf,.eps} %% need no \usepackage{Sweave} \author{Achim Zeileis\\Universit\"at Innsbruck \And Gabor Grothendieck\\GKX Associates Inc.} \Plainauthor{Achim Zeileis, Gabor Grothendieck} \title{\pkg{zoo}: An \proglang{S3} Class and Methods for Indexed Totally Ordered Observations} \Plaintitle{zoo: An S3 Class and Methods for Indexed Totally Ordered Observations} \Keywords{totally ordered observations, irregular time series, regular time series, \proglang{S3}, \proglang{R}} \Plainkeywords{totally ordered observations, irregular time series, regular time series, S3, R} \Abstract{ A previous version to this introduction to the \proglang{R} package \pkg{zoo} has been published as \cite{zoo:Zeileis+Grothendieck:2005} in the \emph{Journal of Statistical Software}. \pkg{zoo} is an \proglang{R} package providing an \proglang{S3} class with methods for indexed totally ordered observations, such as discrete irregular time series. Its key design goals are independence of a particular index/time/date class and consistency with base \proglang{R} and the \code{"ts"} class for regular time series. This paper describes how these are achieved within \pkg{zoo} and provides several illustrations of the available methods for \code{"zoo"} objects which include plotting, merging and binding, several mathematical operations, extracting and replacing data and index, coercion and \code{NA} handling. A subclass \code{"zooreg"} embeds regular time series into the \code{"zoo"} framework and thus bridges the gap between regular and irregular time series classes in \proglang{R}. } \Address{ Achim Zeileis\\ Universit\"at Innsbruck\\ E-mail: \email{Achim.Zeileis@R-project.org}\\ Gabor Grothendieck\\ GKX Associates Inc.\\ E-mail: \email{ggrothendieck@gmail.com} } \begin{document} \SweaveOpts{engine=R,eps=FALSE} %\VignetteIndexEntry{zoo: An S3 Class and Methods for Indexed Totally Ordered Observations} %\VignetteDepends{zoo,timeDate,tseries,strucchange,DAAG} %\VignetteKeywords{totally ordered observations, irregular time series, S3, R} %\VignettePackage{zoo} <>= library("zoo") library("tseries") library("strucchange") library("timeDate") online <- FALSE ## if set to FALSE the local copy of MSFT.rda ## is used instead of get.hist.quote() options(prompt = "R> ") Sys.setenv(TZ = "GMT") @ \section{Introduction} \label{sec:intro} The \proglang{R} system for statistical computing \citep[\url{http://www.R-project.org/}]{zoo:R:2008} ships with a class for regularly spaced time series, \code{"ts"} in package \pkg{stats}, but has no native class for irregularly spaced time series. With the increased interest in computational finance with \proglang{R} over the last years several implementations of classes for irregular time series emerged which are aimed particularly at finance applications. These include the \proglang{S4} classes \code{"timeSeries"} in package \pkg{timeSeries} (previously \pkg{fSeries}) from the \pkg{Rmetrics} suite \citep{zoo:Rmetrics:2008}, \code{"its"} in package \pkg{its} \citep{zoo:its:2004} and the \proglang{S3} class \code{"irts"} in package \pkg{tseries} \citep{zoo:tseries:2007}. With these packages available, why would anybody want yet another package providing infrastructure for irregular time series? The above mentioned implementations have in common that they are restricted to a particular class for the time scale: the former implementation comes with its own time class \code{"timeDate"} from package \pkg{timeDate} (previously \pkg{fCalendar}) built on top of the \code{"POSIXct"} class available in base \proglang{R} whereas the latter two use \code{"POSIXct"} directly. And this was the starting point for the \pkg{zoo} project: the first author of the present paper needed more general support for ordered observations, independent of a particular index class, for the package \pkg{strucchange} \citep{zoo:Zeileis+Leisch+Hornik:2002}. Hence, the package was called \pkg{zoo} which stands for \underline{Z}'s \underline{o}rdered \underline{o}bservations. Since the first release, a major part of the additions to \pkg{zoo} were provided by the second author of this paper, so that the name of the package does not really reflect the authorship anymore. Nevertheless, independence of a particular index class remained the most important design goal. While the package evolved to its current status, a second key design goal became more and more clear: to provide methods to standard generic functions for the \code{"zoo"} class that are similar to those for the \code{"ts"} class (and base \proglang{R} in general) such that the usage of \pkg{zoo} is very intuitive because few additional commands have to be learned. This paper describes how these design goals are implemented in \pkg{zoo}. The resulting package provides the \code{"zoo"} class which offers an extensive (and still growing) set of standard and new methods for working with indexed observations and `talks' to the classes \code{"ts"}, \code{"its"}, \code{"irts"} and \code{"timeSeries"}. \citep[In addition to these independent approaches, the class \code{"xts"} built upon \code{"zoo"} was recently introduced by][.]{zoo:xts:2008}. \pkg{zoo} also bridges the gap between regular and irregular time series by providing coercion with (virtually) no loss of information between \code{"ts"} and \code{"zoo"}. With these tools \pkg{zoo} provides the basic infrastructure for working with indexed totally ordered observations and the package can be either employed by users directly or can be a basic ingredient on top of which other more specialized applications can be built. The remainder of the paper is organized as follows: Section~\ref{sec:zoo-class} explains how \code{"zoo"} objects are created and illustrates how the corresponding methods for plotting, merging and binding, several mathematical operations, extracting and replacing data and index, coercion and \code{NA} handling can be used. Section~\ref{sec:combining} outlines how other packages can build on this basic infrastructure. Section~\ref{sec:summary} gives a few summarizing remarks and an outlook on future developments. Finally, an appendix provides a reference card that gives an overview of the functionality contained in \pkg{zoo}. \section[The class "zoo" and its methods]{The class \code{"zoo"} and its methods} \label{sec:zoo-class} This section describes how \code{"zoo"} series can be created and subsequently manipulated, visualized, combined or coerced to other classes. In Section~\ref{sec:zoo}, the general class \code{"zoo"} for totally ordered series is described. Subsequently, in Section~\ref{sec:zooreg}, the subclass \code{"zooreg"} for regular \code{"zoo"} series, i.e., series which have an index with a specified frequency, is discussed. The methods illustrated in the remainder of the section are mostly the same for both \code{"zoo"} and \code{"zooreg"} objects and hence do not have to be discussed separately. The few differences in merging and binding are briefly highlighted in Section~\ref{sec:merge}. \subsection[Creation of "zoo" objects]{Creation of \code{"zoo"} objects} \label{sec:zoo} The simple idea for the creation of \code{"zoo"} objects is to have some vector or matrix of observations \code{x} which are totally ordered by some index vector. In time series applications, this index is a measure of time but every other numeric, character or even more abstract vector that provides a total ordering of the observations is also suitable. Objects of class \code{"zoo"} are created by the function \begin{Scode} zoo(x, order.by) \end{Scode} where \code{x} is the vector or matrix of observations\footnote{In principle, more general objects can be indexed, but currently \pkg{zoo} does not support this. Development plans are that \pkg{zoo} should eventually support indexed factors, data frames and lists.} and \code{order.by} is the index by which the observations should be ordered. It has to be of the same length as \code{NROW(x)}, i.e., either the same length as \code{x} for vectors or the same number of rows for matrices.\footnote{The only case where this restriction is not imposed is for zero-length vectors, i.e., vectors that only have an index but no data.} The \code{"zoo"} object created is essentially the vector/matrix as before but has an additional \code{"index"} attribute in which the index is stored.\footnote{There is some limited support for indexed factors available in which case the \code{"zoo"} object also has an attribute \code{"oclass"} with the original class of \code{x}. This feature is still under development and might change in future versions.} Both the observations in the vector/matrix \code{x} and the index \code{order.by} can, in principle, be of arbitrary classes. However, most of the following methods (plotting, aggregating, mathematical operations) for \code{"zoo"} objects are typically only useful for numeric observations \code{x}. Special effort in the design was put into independence from a particular class for the index vector. In \pkg{zoo}, it is assumed that combination \code{c()}, querying the \code{length()}, value matching \code{MATCH()}, subsetting \code{[}, and, of course, ordering \code{ORDER()} work when applied to the index. In addition, an \code{as.character()} method might improve printed output\footnote{If an \code{as.character()} method is already defined, but gives not the desired output for printing, then an \code{index2char()} method can be defined. This is a generic convenience function used for creating character representations of the index vector and it defaults to using \code{as.character()}.} and \code{as.numeric()} could be used for computing distances between indexes, e.g., in interpolation. Both methods are not necessary for working with \code{"zoo"} objects but could be used if available. All these methods are available, e.g., for standard numeric and character vectors and for vectors of classes \code{"Date"}, \code{"POSIXct"} or \code{"times"} from package \pkg{chron} and \code{"timeDate"} in \pkg{timeDate}. Because not all required methods used to be available for \code{"timeDate"} in older versions of \pkg{fCalendar}, Section~\ref{sec:fCalendar} has a rather outdated example how to provide such methods so that \code{"zoo"} objects work with \code{"timeDate"} indexes. To achieve this independence of the index class, new generic functions for ordering (\code{ORDER()}) and value matching (\code{MATCH()}) are introduced as the corresponding base functions \code{order()} and \code{match()} are non-generic. The default methods simply call the corresponding base functions, i.e., no new method needs to be introduced for a particular index class if the non-generic functions \code{order()} and \code{match()} work for this class. \emph{\proglang{R} now also provides a new generic \code{xtfrm()} which was not available when the new generic \code{ORDER()} was introduced. If there is a \code{xtfrm()} for a class, the default \code{ORDER()} method typically works.} To illustrate the usage of \code{zoo()}, we first load the package and set the random seed to make the examples in this paper exactly reproducible. <>= library("zoo") set.seed(1071) @ Then, we create two vectors \code{z1} and \code{z2} with \code{"POSIXct"} indexes, one with random observations <>= z1.index <- ISOdatetime(2004, rep(1:2,5), sample(28,10), 0, 0, 0) z1.data <- rnorm(10) z1 <- zoo(z1.data, z1.index) @ and one with a sine wave <>= z2.index <- as.POSIXct(paste(2004, rep(1:2, 5), sample(1:28, 10), sep = "-")) z2.data <- sin(2*1:10/pi) z2 <- zoo(z2.data, z2.index) @ Furthermore, we create a matrix \code{Z} with random observations and a \code{"Date"} index <>= Z.index <- as.Date(sample(12450:12500, 10)) Z.data <- matrix(rnorm(30), ncol = 3) colnames(Z.data) <- c("Aa", "Bb", "Cc") Z <- zoo(Z.data, Z.index) @ In the examples above, the generation of indexes looks a bit awkward due to the fact the indexes need to be randomly generated (and there are no special functions for random indexes because these are rarely needed in practice). In ``real world'' applications, the indexes are typically part of the raw data set read into \proglang{R} so the code would be even simpler. See Section~\ref{sec:combining} for such examples.\footnote{Note, that in the code above a new \code{as.Date} method, provided in \pkg{zoo}, is used to convert days since 1970-01-01 to class \code{"Date"}. See the respective help page for more details.} Methods to several standard generic functions are available for \code{"zoo"} objects, such as \code{print}, \code{summary}, \code{str}, \code{head}, \code{tail} and \code{[} (subsetting), a few of which are illustrated in the following. There are three printing code styles for \code{"zoo"} objects: vectors are by default printed in \code{"horizontal"} style <>= z1 z1[3:7] @ and matrices in \code{"vertical"} style <>= Z Z[1:3, 2:3] @ Additionally, there is a \code{"plain"} style which simply first prints the data and then the index. Above, we have illustrated that \code{"zoo"} series can be indexed like vectors or matrices respectively, i.e., with integers correponding to their observation number (and column number). But for indexed observations, one would obviously also like to be able to index with the index class. This is also available in \code{[} which only uses vector/matrix-type subsetting if its first argument is of class \code{"numeric"}, \code{"integer"} or \code{"logical"}. <>= z1[ISOdatetime(2004, 1, c(14, 25), 0, 0, 0)] @ If the index class happens to be \code{"numeric"}, the index has to be either insulated in \code{I()} like \code{z[I(i)]} or the \code{window()} method can be used (see Section~\ref{sec:window}). Summaries and most other methods for \code{"zoo"} objects are carried out column wise, reflecting the rectangular structure. In addition, a summary of the index is provided. <>= summary(z1) summary(Z) @ \subsection[Creation of "zooreg" objects]{Creation of \code{"zooreg"} objects} \label{sec:zooreg} Strictly regular series are such series observations where the distance between the indexes of every two adjacent observations is the same. Such series can also be described by their frequency, i.e., the reciprocal value of the distance between two observations. As \code{"zoo"} can be used to store series with arbitrary type of index, it can, of course, also be used to store series with regular indexes. So why should this case be given special attention, in particular as there is already the \code{"ts"} class devoted entirely to regular series? There are two reasons: First, to be able to convert back and forth between \code{"ts"} and \code{"zoo"}, the frequency of a certain series needs to be stored on the \code{"zoo"} side. Second, \code{"ts"} is limited to strictly regular series and the regularity is lost if some internal observations are omitted. Series that can be created by omitting some internal observations from strictly regular series will in the following be refered to as being (weakly) regular. Therefore, a class that bridges the gap between irregular and strictly regular series is needed and \code{"zooreg"} fills this gap. Objects of class \code{"zooreg"} inherit from class \code{"zoo"} but have an additional attribute \code{"frequency"} in which the frequency of the series is stored. Therefore, they can be employed to represent both strictly and weakly regular series. To create a \code{"zooreg"} object, either the command \code{zoo()} can be used or the command \code{zooreg()}. \begin{Scode} zoo(x, order.by, frequency) zooreg(data, start, end, frequency, deltat, ts.eps, order.by) \end{Scode} If \code{zoo()} is called as in the previous section but with an additional \code{frequency} argument, it is checked whether \code{frequency} complies with the index \code{order.by}: if it does an object of class \code{"zooreg"} inheriting from \code{"zoo"} is returned. The command \code{zooreg()} takes mostly the same arguments as \code{ts()}.\footnote{Only if \code{order.by} is specified in the \code{zooreg()} call, then \code{zoo(x, order.by, frequency)} is called.} In both cases, the index class is more restricted than in the plain \code{"zoo"} case. The index must be of a class which can be coerced to \code{"numeric"} (for checking its regularity) and when converted to numeric the index must be expressable as multiples of 1/frequency. Furthermore, adding/substracting a numeric to/from an observation of the index class, should return the correct value of the index class again, i.e., group generic functions \code{Ops} should be defined.\footnote{An application of non-numeric indexes for regular series are the classes \code{"yearmon"} and \code{"yearqtr"} which are designed for monthly and quarterly series respectively and are discussed in Section~\ref{sec:yearmon}.} The following calls yield equivalent series <>= zr1 <- zooreg(sin(1:9), start = 2000, frequency = 4) zr2 <- zoo(sin(1:9), seq(2000, 2002, by = 1/4), 4) zr1 zr2 @ to which methods to standard generic functions for regular series can be applied, such as \code{frequency}, \code{deltat}, \code{cycle}. As stated above, the advantage of \code{"zooreg"} series is that they remain regular even if an internal observation is dropped: <>= zr1 <- zr1[-c(3, 5)] zr1 class(zr1) frequency(zr1) @ This facilitates \code{NA} handling significantly compared to \code{"ts"} and makes \code{"zooreg"} a much more attractive data type, e.g., for time series regression. \code{zooreg()} can also deal with non-numeric indexes provided that adding \code{"numeric"} observations to the index class preserves the class and does not coerce to \code{"numeric"}. <>= zooreg(1:5, start = as.Date("2005-01-01")) @ To check whether a certain series is (strictly) regular, the new generic function \code{is.regular(x, strict = FALSE)} can be used: <>= is.regular(zr1) is.regular(zr1, strict = TRUE) @ This function (and also the \code{frequency}, \code{deltat} and \code{cycle}) also work for \code{"zoo"} objects if the regularity can still be inferred from the data: <>= zr1 <- as.zoo(zr1) zr1 class(zr1) is.regular(zr1) frequency(zr1) @ Of course, inferring the underlying regularity is not always reliable and it is safer to store a regular series as a \code{"zooreg"} object if it is intended to be a regular series. If a weakly regular series is coerced to \code{"ts"} the missing observations are filled with \code{NA}s (see also Section~\ref{sec:NA}). For strictly regular series with numeric index, the class can be switched between \code{"zoo"} and \code{"ts"} without loss of information. <>= as.ts(zr1) identical(zr2, as.zoo(as.ts(zr2))) @ This enables direct use of functions such as \code{acf}, \code{arima}, \code{stl} etc. on \code{"zooreg"} objects as these methods coerce to \code{"ts"} first. The result only has to be coerced back to \code{"zoo"}, if appropriate. \subsection{Plotting} \label{sec:plot} The \code{plot} method for \code{"zoo"} objects, in particular for multivariate \code{"zoo"} series, is based on the corresponding method for (multivariate) regular time series. It relies on \code{plot} and \code{lines} methods being available for the index class which can plot the index against the observations. By default the \code{plot} method creates a panel for each series <>= plot(Z) @ but can also display all series in a single panel <>= plot(Z, plot.type = "single", col = 2:4) @ \begin{figure}[b!] \begin{center} <>= <> @ \caption{\label{fig:plot2} Example of a single panel plot} \end{center} \end{figure} \begin{figure}[p] \begin{center} <>= <> @ <>= plot(Z, type = "b", lty = 1:3, pch = list(Aa = 1:5, Bb = 2, Cc = 4), col = list(Bb = 2, 4)) @ \caption{\label{fig:plot13} Examples of multiple panel plots} \end{center} \end{figure} In both cases additional graphical parameters like color \code{col}, plotting character \code{pch} and line type \code{lty} can be expanded to the number of series. But the \code{plot} method for \code{"zoo"} objects offers some more flexibility in specification of graphical parameters as in <>= <> @ The argument \code{lty} behaves as before and sets every series in another line type. The \code{pch} argument is a named list that assigns to each series a different vector of plotting characters each of which is expanded to the number of observations. Such a list does not necessarily have to include the names of all series, but can also specify a subset. For the remaining series the default parameter is then used which can again be changed: e.g., in the above example the \code{col} argument is set to display the series \code{"Bb"} in red and all remaining series in blue. The results of the multiple panel plots are depicted in Figure~\ref{fig:plot13} and the single panel plot in Figure~\ref{fig:plot2}. \subsection{Merging and binding} \label{sec:merge} As for many rectangular data formats in \proglang{R}, there are both methods for combining the rows and columns of \code{"zoo"} objects respectively. For the \code{rbind} method the number of columns of the combined objects has to be identical and the indexes may not overlap. <>= rbind(z1[5:10], z1[2:3]) @ The \code{c} method simply calls \code{rbind} and hence behaves in the same way. The \code{cbind} method by default combines the columns by the union of the indexes and fills the created gaps by \code{NA}s. <>= cbind(z1, z2) @ In fact, the \code{cbind} method is synonymous with the \code{merge} method\footnote{Note, that in some situations the column naming in the resulting object is somewhat problematic in the \code{cbind} method and the \code{merge} method might provide better formatting of the column names.} except that the latter provides additional arguments which allow for combining the columns by the intersection of the indexes using the argument \code{all = FALSE} <>= merge(z1, z2, all = FALSE) @ Additionally, the filling pattern can be changed in \code{merge}, the naming of the columns can be modified and the return class of the result can be specified. In the case of merging of objects with different index classes, \proglang{R} gives a warning and tries to coerce the indexes. Merging objects with different index classes is generally discouraged---if it is used nevertheless, it is the responsibility of the user to ensure that the result is as intended. If at least one of the merged/binded objects was a \code{"zooreg"} object, then \code{merge} tries to return a \code{"zooreg"} object. This is done by assessing whether there is a common maximal frequency and by checking whether the resulting index is still (weakly) regular. If non-\code{"zoo"} objects are included in merging, then \code{merge} gives plain vectors/factors/matrices the index of the first argument (if it is of the same length). Scalars are always added for the full index without missing values. <>= merge(z1, pi, 1:10) @ Another function which performs operations along a subset of indexes is \code{aggregate}, which is discussed in this section although it does not combine several objects. Using the \code{aggregate} method, \code{"zoo"} objects are split into subsets along a coarser index grid, summary statistics are computed for each and then the reduced object is returned. In the following example, first a function is set up which returns for a given \code{"Date"} value the corresponding first of the month. This function is then used to compute the coarser grid for the \code{aggregate} call: in the first example, the grouping is computed explicitely by \verb/firstofmonth(index(Z))/ and the mean of the observations in the month is returned---in the second example, only the function that computes the grouping (when applied to \verb/index(Z)/) is supplied and the first observation is used for aggregation. <>= firstofmonth <- function(x) as.Date(sub("..$", "01", format(x))) aggregate(Z, firstofmonth(index(Z)), mean) aggregate(Z, firstofmonth, head, 1) @ The opposite of aggregation is disaggregation. For example, the \code{Nile} dataset is an annual \code{"ts"} class series. To disaggregate it into a quarterly series, convert it to a \code{"zoo} class series, insert intermediate quarterly points containing \code{NA} values and then fill the \code{NA} values using \code{na.approx}, \code{na.locf} or \code{na.spline}: <>= Nile.na <- merge(as.zoo(Nile), zoo(, seq(start(Nile)[1], end(Nile)[1], 1/4))) head(as.zoo(Nile)) head(na.approx(Nile.na)) head(na.locf(Nile.na)) head(na.spline(Nile.na)) @ \subsection{Mathematical operations} \label{sec:Ops} To allow for standard mathematical operations among \code{"zoo"} objects, \pkg{zoo} extends group generic functions \code{Ops}. These perform the operations only for the intersection of the indexes of the objects. As an example, the summation and logical comparison with $<$ of \code{z1} and \code{z2} yield <>= z1 + z2 z1 < z2 @ Additionally, methods for transposing \code{t} of \code{"zoo"} objects---which coerces to a matrix before---and computing cumulative quantities such as \code{cumsum}, \code{cumprod}, \code{cummin}, \code{cummax} which are all applied column wise. <>= cumsum(Z) @ \subsection{Extracting and replacing the data and the index} \label{sec:window} \pkg{zoo} provides several generic functions and methods to work on the data contained in a \code{"zoo"} object, the index (or time) attribute associated to it, and on both data and index. The data stored in \code{"zoo"} objects can be extracted by \code{coredata} which strips off all \code{"zoo"}-specific attributes and it can be replaced using \code{coredata<-}. Both are new generic functions\footnote{The \code{coredata} functionality is similar in spirit to the \code{core} function in \pkg{its} and \code{value} in \pkg{tseries}. However, the focus of those functions is somewhat narrower and we try to provide more general purpose generic functions. See the respective manual page for more details.} with methods for \code{"zoo"} objects as illustrated in the following example. <>= coredata(z1) coredata(z1) <- 1:10 z1 @ The index associated with a \code{"zoo"} object can be extracted by \code{index} and modified by \mbox{\code{index<-}.} As the interpretation of the index as ``time'' in time series applications is natural, there are also synonymous methods \code{time} and \code{time<-}. Hence, the commands \code{index(z2)} and \code{time(z2)} return equivalent results. <>= index(z2) @ The index scale of \code{z2} can be changed to that of \code{z1} by <>= index(z2) <- index(z1) z2 @ The start and the end of the index/time vector can be queried by \code{start} and \code{end}: <>= start(z1) end(z1) @ To work on both data and index/time, \pkg{zoo} provides \code{window} and \code{window<-} methods for \code{"zoo"} objects. In both cases the window is specified by \begin{Scode} window(x, index, start, end) \end{Scode} where \code{x} is the \code{"zoo"} object, \code{index} is a set of indexes to be selected (by default the full index of \code{x}) and \code{start} and \code{end} can be used to restrict the \code{index} set. <>= window(Z, start = as.Date("2004-03-01")) window(Z, index = index(Z)[5:8], end = as.Date("2004-03-01")) @ The first example selects all observations starting from 2004-03-01 whereas the second selects from the from the 5th to 8th observation those up to 2004-03-01. The same syntax can be used for the corresponding replacement function. <>= window(z1, end = as.POSIXct("2004-02-01")) <- 9:5 z1 @ Two methods that are standard in time series applications are \code{lag} and \code{diff}. These are available with the same arguments as the \code{"ts"} methods.\footnote{\code{diff} also has an additional argument that also allows for geometric and not only allows arithmetic differences. Furthermore, note the sign of the lag in \code{lag} which behaves like the \code{"ts"} method, i.e., by default it is positive and shifts the observations \emph{forward}, to obtain the more standard \emph{backward} shift the lag has to be negative.} <>= lag(z1, k = -1) merge(z1, lag(z1, k = 1)) diff(z1) @ \subsection[Coercion to and from "zoo"]{Coercion to and from \code{"zoo"}} \label{sec:as.zoo} Coercion to and from \code{"zoo"} objects is available for objects of various classes, in particular \code{"ts"}, \code{"irts"} and \code{"its"} objects can be coerced to \code{"zoo"} and back if the index is of the appropriate class.\footnote{Coercion from \code{"zoo"} to \code{"irts"} is contained in the \pkg{tseries} package.} Coercion between \code{"zooreg"} and \code{"zoo"} is also available and is essentially dropping the \code{"frequency"} attribute or trying to add one, respectively. Furthermore, \code{"zoo"} objects can be coerced to vectors, matrices, lists and data frames (the latter dropping the index/time attribute). A simple example is <>= as.data.frame(Z) @ \subsection[NA handling]{\code{NA} handling} \label{sec:NA} Four methods for dealing with \code{NA}s (missing observations) in the observations are applicable to \code{"zoo"} objects: \code{na.omit}, \code{na.contiguous}, \code{na.approx} and \code{na.locf}. \code{na.omit}---or its default method to be more precise---returns a \code{"zoo"} object with incomplete observations removed. \code{na.contiguous} extracts the longest consecutive stretch of non-missing values. Furthermore, new generic functions \code{na.approx} and \code{na.locf} and corresponding default methods are introduced in \pkg{zoo}. The former replaces \code{NA}s by linear interpolation (using the function \code{approx}) and the name of the latter stands for \underline{l}ast \underline{o}bservation \underline{c}arried \underline{f}orward. It replaces missing observations by the most recent non-\code{NA} prior to it. Leading \code{NA}s, which cannot be replaced by previous observations, are removed in both functions by default. <>= z1[sample(1:10, 3)] <- NA z1 na.omit(z1) na.contiguous(z1) na.approx(z1) na.approx(z1, 1:NROW(z1)) na.locf(z1) @ As the above example illustrates, \code{na.approx} uses by default the underlying time scale for interpolation. This can be changed, e.g., to an equidistant spacing, by setting the second argument of \code{na.approx}. \subsection{Rolling functions} \label{sec:rolling} A typical task to be performed on ordered observations is to evaluate some function, e.g., computing the mean, in a window of observations that is moved over the full sample period. The resulting statistics are usually synonymously referred to as rolling/running/moving statistics. In \pkg{zoo}, the generic function \code{rollapply}\footnote{In previous versions of \pkg{zoo}, this function was called \code{rapply}. It was renamed because from \proglang{R}~2.4.0 on, base \proglang{R} provides a different function \code{rapply} for recursive (and not rolling) application of functions. The function \code{zoo::rapply} is still provided for backward compatibility, however it dispatches now to \code{rollapply} methods.} is provided along with a \code{"zoo"} and a \code{"ts"} method. The most important arguments are \begin{Scode} rollapply(data, width, FUN) \end{Scode} where the function \code{FUN} is applied to a rolling window of size \code{width} of the observations \code{data}. The function \code{rollapply} by default only evaluates the function for windows of full size \code{width} and then the result has \code{width - 1} fewer observations than the original series and is aligned at the center of the rolling window. Setting further arguments such as \code{partial}, \code{align}, or \code{fill} also allows for rolling computations on partial windows with arbitrary aligning and flexible filling. For example, without partial evaluation the `lost' observations could be filled with \code{NA}s and aligned at the left of the sample. <>= rollapply(Z, 5, sd) rollapply(Z, 5, sd, fill = NA, align = "left") @ To improve the performance of \code{rollapply(x, k, }\textit{foo}\code{)} for some frequently used functions \textit{foo}, more efficient implementations \code{roll}\textit{foo}\code{(x, k)} are available (and also called by \code{rollapply}). Currently, these are the generic functions \code{rollmean}, \code{rollmedian} and \code{rollmax} which have methods for \code{"zoo"} and \code{"ts"} series and a default method for plain vectors. <>= rollmean(z2, 5, fill = NA) @ \section[Combining zoo with other packages]{Combining \pkg{zoo} with other packages} \label{sec:combining} The main purpose of the package \pkg{zoo} is to provide basic infrastructure for working with indexed totally ordered observations that can be either employed by users directly or can be a basic ingredient on top of which other packages can build. The latter is illustrated with a few brief examples involving the packages \pkg{strucchange}, \pkg{tseries} and \pkg{timeDate}/\pkg{fCalendar} in this section. Finally, the classes \code{"yearmon"} and \code{"yearqtr"} (provided in \pkg{zoo}) are used for illustrating how \pkg{zoo} can be extended by creating a new index class. \subsection[strucchange: Empirical fluctuation processes]{\pkg{strucchange}: Empirical fluctuation processes} \label{sec:strucchange} The package \pkg{strucchange} provides a collection of methods for testing, monitoring and dating structural changes, in particular in linear regression models. Tests for structural change assess whether the parameters of a model remain constant over an ordering with respect to a specified variable, usually time. To adequately store and visualize empirical fluctuation processes which capture instabilities over this ordering, a data type for indexed ordered observations is required. This was the motivation for starting the \pkg{zoo} project. A simple example for the need of \code{"zoo"} objects in \pkg{strucchange} which can not be (easily) implemented by other irregular time series classes available in \proglang{R} is described in the following. We assess the constancy of the electrical resistance over the apparent juice content of kiwi fruits.\footnote{A different approach would be to test whether the slope of a regression of electrical resistance on juice content changes with increasing juice content, i.e., to test for instabilities in \code{ohms \~{} juice} instead of \code{ohms \~{} 1}. Both lead to similar results.} The data set \code{fruitohms} is contained in the \pkg{DAAG} package \citep{zoo:DAAG:2004}. The fitted \code{ocus} object contains the OLS-based CUSUM process for the mean of the electrical resistance (variable \code{ohms}) indexed by the juice content (variable \code{juice}). <>= library("strucchange") library("DAAG") data("fruitohms") ocus <- gefp(ohms ~ 1, order.by = ~ juice, data = fruitohms) @ \begin{figure}[h!] \begin{center} <>= plot(ocus) @ \caption{\label{fig:strucchange} Empirical M-fluctuation process for \code{fruitohms} data} \end{center} \end{figure} This OLS-based CUSUM process can be visualized using the \code{plot} method for \code{"gefp"} objects which builds on the \code{"zoo"} method and yields in this case the plot in Figure~\ref{fig:strucchange} showing the process which crosses its 5\% critical value and thus signals a significant decrease in the mean electrical resistance over the juice content. For more information on the package \pkg{strucchange} and the function \code{gefp} see \cite{zoo:Zeileis+Leisch+Hornik:2002} and \cite{zoo:Zeileis:2005}. \subsection[tseries: Historical financial data]{\pkg{tseries}: Historical financial data} \label{sec:tseries} \emph{This section was written when \pkg{tseries} did not yet support \code{"zoo"} series directly. For historical reasons and completeness, the example is still included but for practical purposes it is not relevant anymore because, from version 0.9-30 on, \code{get.hist.quote} returns a \code{"zoo"} series by default.} A typical application for irregular time series which became increasingly important over the last years in computational statistics and finance is daily (or higher frequency) financial data. The package \pkg{tseries} provides the function \code{get.hist.quote} for obtaining historical financial data by querying Yahoo!\ Finance at \url{http://finance.yahoo.com/}, an online portal quoting data provided by Reuters. The following code queries the quotes of Microsoft Corp.\ starting from 2001-01-01 until 2004-09-30: <>= library("tseries") MSFT <- get.hist.quote(instrument = "MSFT", start = "2001-01-01", end = "2004-09-30", origin = "1970-01-01", retclass = "ts") @ <>= if(online) { MSFT <- get.hist.quote("MSFT", start = "2001-01-01", end = "2004-09-30", origin = "1970-01-01", retclass = "ts") save(MSFT, file = "MSFT.rda", compress = TRUE) } else { load("MSFT.rda") } @ In the returned \code{MSFT} object the irregular data is stored by extending it in a regular grid and filling the gaps with \code{NA}s. The time is stored in days starting from an \code{origin}, in this case specified to be 1970-01-01, the origin used by the \code{"Date"} class. This series can be transformed easily into a \code{"zoo"} series using a \code{"Date"} index. <>= MSFT <- as.zoo(MSFT) index(MSFT) <- as.Date(index(MSFT)) MSFT <- na.omit(MSFT) @ Because this is daily data, the series has a natural underlying regularity. Thus, \code{as.zoo()} returns a \code{"zooreg"} object by default. To treat it as an irregular series \code{as.zoo()} can be applied a second time, yielding a \code{"zoo"} series. The corresponding log-difference returns are depicted in Figure~\ref{fig:tseries}. <>= MSFT <- as.zoo(MSFT) @ \begin{figure}[h!] \begin{center} <>= plot(diff(log(MSFT))) @ \caption{\label{fig:tseries} Log-difference returns for Microsoft Corp.} \end{center} \end{figure} \subsection[timeDate/fCalendar: Indexes of class "timeDate"]{\pkg{timeDate}/\pkg{fCalendar}: Indexes of class \code{"timeDate"}} \label{sec:timeDate} \emph{The original version of this section was written when \pkg{fCalendar} (now: \pkg{timeDate}) and \pkg{zoo} did not yet include enough methods to attach \code{"timeDate"} indexes to \code{"zoo"} series. For historical reasons and completeness, we still briefly comment on the communcation between the packages and their classes.} Although the methods in \pkg{zoo} work out of the box for many index classes, it might be necessary for some index classes to provide \code{c()}, \code{length()}, \code{[}, \code{ORDER()} and \code{MATCH()} methods such that the methods in \pkg{zoo} work properly. Previously, this was the case \code{"timeDate"} from the \pkg{fCalendar} package which is why it was used as an example in this vigntte. Meanwhile however, both \pkg{zoo} and \pkg{fCalendar}/\pkg{timeDate} have been enhanced: The latter contains the methods for \code{c()}, \code{length()}, and \code{[}, while \pkg{zoo} has methods for \code{ORDER()} and \code{MATCH()} for class \code{"timeDate"}. The last two functions essentially work by coercing to the underlying \code{"POSIXct"} and then using the associated methods. The following example illustrates how \code{z2} can be transformed to use the \code{"timeDate"} class. <>= library("timeDate") z2td <- zoo(coredata(z2), timeDate(index(z2), FinCenter = "GMT")) z2td @ \subsection[The classes "yearmon" and "yearqtr": Roll your own index]{The classes \code{"yearmon"} and \code{"yearqtr"}: Roll your own index} \label{sec:yearmon} One of the strengths of the \pkg{zoo} package is its independence of the index class, such that the index can be easily customized. The previous section already explained how an existing class (\code{"timeDate"}) can be used as the index if the necessary methods are created. This section has a similar but slightly different focus: it describes how new index classes can be created addressing a certain type of indexes. These classes are \code{"yearmon"} and \code{"yearqtr"} (already contained in \pkg{zoo}) which provide indexes for monthly and quarterly data respectively. As the code is virtually identical for both classes---except that one has the frequency 12 and the other 4---we will only discuss \code{"yearmon"} explicitly. Of course, monthly data can simply be stored using a numeric index just as the class \code{"ts"} does. The problem is that this does not have the meta-information attached that this is really specifying monthly data which is in \code{"yearmon"} simply added by a class attribute. Hence, the class creator is simply defined as \begin{Scode} yearmon <- function(x) structure(floor(12*x + .0001)/12, class = "yearmon") \end{Scode} which is very similar to the \code{as.yearmon} coercion functions provided. As \code{"yearmon"} data is now explicitly declared to describe monthly data, this can be exploited for coercion to other time classes: either to coarser time scales such as \code{"yearqtr"} or to finer time scales such as \code{"Date"}, \code{"POSIXct"} or \code{"POSIXlt"} which by default associate the first day within a month with a \code{"yearmon"} observation. Adding a \code{format} and \code{as.character} method produces human readable character representations of \code{"yearmon"} data and \code{Ops} and \code{MATCH} methods complete the methods needed for conveniently working with monthly data in \pkg{zoo}. Note, that all of these methods are very simple and rather obvious (as can be seen in the \pkg{zoo} sources), but prove very helpful in the following examples. First, we create a regular series \code{zr3} with \code{"yearmon"} index which leads to improved printing compared to the regular series \code{zr1} and \code{zr2} from Section~\ref{sec:zooreg}. <>= zr3 <- zooreg(rnorm(9), start = as.yearmon(2000), frequency = 12) zr3 @ This could be aggregated to quarterly data via <>= aggregate(zr3, as.yearqtr, mean) @ The index can easily be transformed to \code{"Date"}, the default being the first day of the month but which can also be changed to the last day of the month. <>= as.Date(index(zr3)) as.Date(index(zr3), frac = 1) @ Furthermore, \code{"yearmon"} indexes can easily be coerced to \code{"POSIXct"} such that the series could be exported as a \code{"its"} or \code{"irts"} series. <>= index(zr3) <- as.POSIXct(index(zr3)) as.irts(zr3) @ Again, this functionality makes switching between different time scales or index representations particularly easy and \pkg{zoo} provides the user with the flexibility to adjust a certain index to his/her problem of interest. \section{Summary and outlook} \label{sec:summary} The package \pkg{zoo} provides an \proglang{S3} class and methods for indexed totally ordered observations, such as both regular and irregular time series. Its key design goals are independence of a particular index class and compatibility with standard generics similar to the behaviour of the corresponding \code{"ts"} methods. This paper describes how these are implemented in \pkg{zoo} and illustrates the usage of the methods for plotting, merging and binding, several mathematical operations, extracting and replacing data and index, coercion and \code{NA} handling. An indexed object of class \code{"zoo"} can be thought of as data plus index where the data are essentially vectors or matrices and the index can be a vector of (in principle) arbitrary class. For (weakly) regular \code{"zooreg"} series, a \code{"frequency"} attribute is stored in addition. Therefore, objects of classes \code{"ts"}, \code{"its"}, \code{"irts"} and \code{"timeSeries"} can easily be transformed into \code{"zoo"} objects---the reverse transformation is also possible provided that the index fulfills the restrictions of the respective class. Hence, the \code{"zoo"} class can also be used as the basis for other classes of indexed observations and more specific functionality can be built on top of it. Furthermore, it bridges the gap between irregular and regular series, facilitating operations such as \code{NA} handling compared to \code{"ts"}. Whereas a lot of effort was put into achieving independence of a particular index class, the types of data that can be indexed with \code{"zoo"} are currently limited to vectors and matrices, typically containing numeric values. Although, there is some limited support available for indexed factors, one important direction for future development of \pkg{zoo} is to add better support for other objects that can also naturally be indexed including specifically factors, data frames and lists. \section*{Computational details} The results in this paper were obtained using \proglang{R} \Sexpr{paste(R.Version()[6:7], collapse = ".")} with the packages \pkg{zoo} \Sexpr{gsub("-", "--", packageDescription("zoo")$Version)}, \pkg{strucchange} \Sexpr{gsub("-", "--", packageDescription("strucchange")$Version)}, \pkg{timeDate} \Sexpr{gsub("-", "--", packageDescription("timeDate")$Version)}, \pkg{tseries} \Sexpr{gsub("-", "--", packageDescription("tseries")$Version)} and \pkg{DAAG} \Sexpr{gsub("-", "--", packageDescription("DAAG")$Version)}. \proglang{R} itself and all packages used are available from CRAN at \url{http://CRAN.R-project.org/}. \bibliography{zoo} \newpage \begin{appendix} \section{Reference card} \input{zoo-refcard-raw} \end{appendix} \end{document} \subsection[stats: (Dynamic) regression modelling]{\pkg{stats}: (Dynamic) regression modelling} \label{sec:stats} \code{zoo} provides a facility for extending regression functions such as \code{lm} to handle time series. One simply encloses the \code{formula} argument in \code{I(...)} and ensures that all variables in the formula are of class \code{"zoo"} or all are of class \code{"ts"}. Basic regression functions, like \code{lm} or \code{glm}, in which regression relationships are specified via a \code{formula} only have limited support for time series regression. The reason is that \code{lm(formula, ...)} calls the generic function \code{model.frame(formula, ...)} to create a a data frame with the variables required. This dispatches to \code{model.frame.formula} which does not deal specifically with (various types of) time series data. Therefore, it would be desirable to dispatch to a specialized \code{model.frame} method depending on the type of the dependent variable. As this is a non-standard dispatch, \pkg{zoo} provides the following mechanism: In the call to the regression function, the \code{formula} is insulated by \code{I()}, e.g., as in \code{lm(I(formula), ...)}, leaving \code{formula} unaltered but returning an object of class \code{"AsIs"}. Then, \code{model.frame.AsIs} is called which examines the dependent variable of the \code{formula} and then dispatches to \code{model.frame.foo} if this is of class \code{"foo"}. In \pkg{zoo}, the methods \code{model.frame.zoo} and \code{model.frame.ts} are provided which are able to create model frames from formulas in which \emph{all} variables are of class \code{"zoo"} or \code{"ts"}, respectively. The advantage of \code{model.frame.zoo} is that it aligns the variables along a common index, it allows the usage of \code{lag} and \code{diff} in the model specification and works with the \code{NA} handling methods described in Section~\ref{sec:NA}. Therefore, dynamic linear regression models can be fit easily using the standard \code{lm} function by just insulating \code{I(formula)} in the corresponding call\footnote{In addition to \code{lm} and \code{glm}, this approach works for many other regression functions including \code{randomForest} ensembles from \pkg{randomForest}, \code{svm} support vector machines from \pkg{e1071}, \code{lqs} resistant regression from \pkg{MASS}, \code{nnet} neural networks from \pkg{nnet}, \code{rq} quantile regression from \pkg{quantreg}, and possibly many others.}. A simple example based on artificial data is given below: the lag of a dependent variable is explained by the first differences of a numeric regressor and an explanatory factor. Note, that the variables have different indexes. First, a linear regression model is fitted, then a quantile regression is carried out for the same equation. \begin{verbatim} yz <- zoo(1:20)^2 xz <- zoo(1:18)^2 fz <- zoo(gl(4, 5)) lm(I(lag(yz) ~ diff(xz) + fz)) library("quantreg") rq(I(lag(yz) ~ diff(xz) + fz)) \end{verbatim} See the help page of \code{model.frame.zoo} for more examples and additional information. Furthermore, note that this feature is under development and might subject to changes in future versions. zoo/vignettes/zoo-refcard.tex0000644000175400001440000000027111747047642016235 0ustar zeileisusers\documentclass[notitle]{Z} \usepackage{a4wide} \begin{document} \pagestyle{empty} \centerline{\Large \bf \pkg{zoo} reference card} \vspace{0.8cm} \input{zoo-refcard-raw} \end{document} zoo/vignettes/zoo-refcard.pdf0000644000175400001440000013666311747047642016225 0ustar zeileisusers%PDF-1.4 % 5 0 obj <>>>stream x[L-j/chE`ĸ-֔3Ȳ̀L, Y'PWQ,Pj"WzV%2[zs_Gk>+-pëW^ W?rk1-`* EQSaA rE#'𠆯 po)_*//'t:VPPi܅dEyy( 555Bp02<!!A h4*:66aK eSqyzֆt:O P/((xbppÇ߯T*fb|ś6mt;wp8{r6lXnho:.:::11`0:***(((66ԩSW\1Lfyjj ðׯ[n۶m:@ X{3 2:zO.eiNNΧ~Z[[aX ?;Q EQE+ ^$矓d2D"}' bO˽t}Yz-D"ٿ?A?bxhh#99  FHHssse2͛ZmjjjWWdbZaDqFEaF2L@" t:]@@ZD"`699  ].NDuuu'&&𝽣###cpp A6o,H^/mqV;虙c522?7p8\..(((--1!!r۷O.+Jf;00@"?+-&Ht\4---mϞ=bF,R KJJ O:!HP=|7D@V1 h4ׯ7!!!jٽ{wUUH,--UTz^oݺURLOO_t)11q׮]t:}nnѣ+L{|;΀>HV# ^hp8* `0xK~gfk$Oo>[oDkׄB+ÇX,AR)Ku:`{j=3gm~mhh(33ѣG,+)))44d2 l6;++n[,*zνѩ5R}󻻻jjjf ˃/ۛb$ILLLVV~l6?}jǏl 믿jkk[\oCJj6O>CRz=jĨ(F1 t0l4'''eV_^WR^ ,a\.W(&==ڵk8K޽kI$Ν;RS~ǘ @p{n{o\ `0z}SS{ˮSǎt\ Km6 !RRRONLL=zTPTVVFDDh47r^ JUpLpxY '''11Q:N>d2Z- tϿs^$? ̙3_|˗bAH$RՃD"qjjL&D"0^wwng6N9?dX) ɄZj`3x4@ hڶ6A練(;88t:@ ɡC-xY"(--x]]] --->|7=zp8\.H$T9 B&8N]] o޼Z,Qs޽-[ ҲN^O u8IIIannn֭AAAyyy333:ѣ7nr8ׯ_Q*0 ;قiٮ_^QQQ]]]]]6W, C2L("h:l?xuuuCCC{xlj7?{L&q~~Y.Ncك&izz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$hLn]>IR'r&YKOҺAi< DvNBPR΁U6z.=w/ps0l&e"؈FD0=S@Ę>0b)">o .bvx f4v0E`GF4yA*\Ce(1r 8{hk;XϷ1gMes0D EC; Pdp7]I^;ֻż3daadէSTA&zn'9.^Y۽,KomGy3Ghc]mO}yκ)ɲ}@Xm~ko&տq2jYMH=#ͫƤ<:h30_ `.GLF_k$*X9)X؍L? 3^}/KRfOdD(ia(n)qY$;rC(@Qݪ?{uNEh^ݴFMjӿaqB T{LKɎNK/s ɱ=w n[_hgȌcQ/gYiE4 H*t62Gڕ-ѤT0dP,FnzKVft7iWKDwy5Ao&8<ϛk63ӫn-P3"U_rA;6Ĕbjt_iv8Pq됚< 7oˡYYȑͪ2qݽ=Ns`Bޔsñtn65@: endstream endobj 8 0 obj << /Type /Page /Contents 10 0 R /Resources 9 0 R /MediaBox [0 0 595.276 841.89] /Thumb 5 0 R /Parent 19 0 R >> endobj 11 0 obj << /D [8 0 R /XYZ 90 757.935 null] >> endobj 12 0 obj << /D [8 0 R /XYZ 90 733.028 null] >> endobj 9 0 obj << /Font << /F22 13 0 R /F26 14 0 R /F29 15 0 R /F34 16 0 R /F8 17 0 R /F37 18 0 R >> /ProcSet [ /PDF /Text ] >> endobj 22 0 obj << /Length 1665 /Filter /FlateDecode >> stream xڽXK6W9y+ԃ@{h@PlNmZY-G eS$dQc#v-~y7YaR.6 Lj&f^|/_9vEywJrY`{m]C?EY??dB MHPFK*I0{wJZn쨋V˽R#TfnZ"H#h$DSYa$.lt5,XMvۆY]+Rh~(܀ fWJqz:OS!W{Ez#F73u myjn)xwүwϺ("N^C,c{t"Dn4 ^{Rm%eYΊ{Y #(vJJ"r7}-`S`dx ~5m`Lq֧-DW/wIj\()ru:k =bb%V-%`Pژ&yErWn96VԪ{q!F~A'ʯ3+VKO-~WB1>{hϣAs3YQڊ㵥&g ߒFh9 9Z]CIEBG2̭aOvZd !QP4B,s Î>5ڌMH(r@^&TۮY0{E3?Ό>x .cI8۪d!P̫d̞&B֘Ku1/`DɅ62%vutiDmy_w2_J#|Ii;({4fQʶll"+Ry_O~{6!EgQ#s6̘m'#QƷ/l[BUnע_P9'P̂}ۍ5,^@kɾI&` $,M+ ͉c!L(%tF.\GP0*|tTbO z&IwkovD[kk =luc݁ 1׆%]kJfJKG58¡3#w3vkνY8} $Y75S怃vQ)P^f6mCj_OԠ<*jޡ$8^)d_; KݒWLG#XEyR[v|}U*S{R{U88!&Z'N<38&ñ2keN!Й8ws2qt/OVe'Dܩy,?M֙j7_\yZ^*p*:N#2E<*IF t`p&L?>@#|i -3";h Nz"b@Ewx㭻y=(?%oN(4. ^e^K8xeQP/q>`A;#`Έ^1hmz<^uIX5̫eȎcPkSbG50+˕ 8n/zqiH3f2!>X˶/w]Q<Pi׫<]'2khgﱒ4h6V9=:V A۽?.j+ endstream endobj 21 0 obj << /Type /Page /Contents 22 0 R /Resources 20 0 R /MediaBox [0 0 595.276 841.89] /Thumb 6 0 R /Parent 19 0 R >> endobj 23 0 obj << /D [21 0 R /XYZ 90 757.935 null] >> endobj 20 0 obj << /Font << /F29 15 0 R /F34 16 0 R /F8 17 0 R >> /ProcSet [ /PDF /Text ] >> endobj 24 0 obj [511.1 460 460 511.1 460 306.7 460 511.1 306.7 306.7 460 255.6 817.8 562.2 511.1 511.1 460 421.7 408.9] endobj 25 0 obj [583.3 555.6 555.6 833.3 833.3 277.8 305.6 500 500 500 500 500 750 444.4 500 722.2 777.8 500 902.8 1013.9 777.8 277.8 277.8 500 833.3 500 833.3 777.8 277.8 388.9 388.9 500 777.8 277.8 333.3 277.8 500 500 500 500 500 500 500 500 500 500 500 277.8 277.8 277.8 777.8 472.2 472.2 777.8 750 708.3 722.2 763.9 680.6 652.8 784.7 750 361.1 513.9 777.8 625 916.7 750 777.8 680.6 777.8 736.1 555.6 722.2 750 750 1027.8 750 750 611.1 277.8 500 277.8 500 277.8 277.8 500 555.6 444.4 555.6 444.4 305.6 500 555.6 277.8 305.6 527.8 277.8 833.3 555.6 500 555.6 527.8 391.7 394.4 388.9 555.6 527.8 722.2 527.8 527.8 444.4] endobj 26 0 obj [525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525 525] endobj 27 0 obj [830.6 881.9 755.6 723.6 904.2 900 436.1 594.4 901.4 691.7 1091.7 900 863.9 786.1 863.9 862.5 638.9 800 884.7 869.4 1188.9 869.4 869.4 702.8 319.4 602.8 319.4 575 319.4 319.4 559 638.9 511.1 638.9 527.1 351.4 575 638.9 319.4 351.4 606.9 319.4 958.3 638.9 575 638.9 606.9 473.6 453.6 447.2 638.9 606.9 830.6 606.9] endobj 28 0 obj [546.9 625 500 625 513.3 343.7 562.5 625 312.5 343.7 593.7 312.5 937.5 625 562.5 625 593.7 459.5] endobj 29 0 obj [500 555.6 527.8 427.8 394.4 390.3 555.6 527.8 722.2 527.8 527.8 444.4] endobj 30 0 obj << /Length1 750 /Length2 1189 /Length3 0 /Length 1718 /Filter /FlateDecode >> stream xڭRyX EyeCBX\#E !-DZ )T*j VlZæb;@gν{~^6D HH42pqQ'EWW4gg{,e#BV$D0>\N( C9` gB p 1$J@2F@' >)H4 0àT!Ę( i `AS,SqsT ʍo?o'in,E@R $|P!SEmn)l W_,f2Kx;h@ -!XڂV/6r۸0" :O^b,¨d*_G< vtG+qx.0Dh d` A%X 9 D"2i)|l] '$=@c3X)NM"O*AdX0c>hdH\K+Ykr6vgk εx TT/g,Aqm]֫s y !y>!ZM ëuZZˎ}}VE۬<Ft̗Ps~GF+O~r9D|ADc.'&]m5銙X2)bӃ]}M0Hi#j}(?Bβeo-?՘ͨ=M}Y~ >Jd4%t=|gsxF]Ԕjer;/!([n{9(5|lrx[Z-<ߡ$zvI m ־)"Zw5~m3΃ O/xSϾ ܨxbvNc_(R0s)PaeOZcMW{ު-ڜ#/sdӆt=DZ!>}je%% 5ǘ_pyI\\Tۧ.FWK6w=Yna8gq~E`*NOMLPSm/RlM?ֶ,aZV{]^rHKzn0\󯧱CF endstream endobj 31 0 obj << /Type /FontDescriptor /FontName /ENGSAK+CMB10 /Flags 4 /FontBBox [-62 -250 1011 750] /Ascent 694 /CapHeight 686 /Descent -194 /ItalicAngle 0 /StemV 108 /XHeight 444 /CharSet (/o/z) /FontFile 30 0 R >> endobj 32 0 obj << /Length1 1080 /Length2 5820 /Length3 0 /Length 6497 /Filter /FlateDecode >> stream xڭe\[A;$rIFR````bn$EE Es{?^׵7pE (i+DDEyxP lʊT77IQ)b 98@%?\H+@uag"`PZ`"b11fB`Ġ?<#!nIyA7?mnLBp4' nԠ7^?l'cG?'_y7O F@H>eN/u fy|=`oBmfp=13P533gsEnG,L XތWϗտT\@\R `Dڠon I`s$@,܌`@qRHRor8dI@ɂl!i7@P 7"ፊoCI]f F7BF7P=A!?o"癰ͦ%EȂO' uE\=*B>P;vwCҚ*U*ZtzgH#+L/2iȷؽ/=:}U?']myYoe>mc6t<ާh=9}2ZbV8nvv#FȌ}s!_xR3S_QARb,U sO: 7h wg- Á<Xg+H^jKÙD|hVDTdפ}ȝϸ.obWVu3(æQDޫX`EOKqowQ/.#n/(m`VE{ϻp>zr[Eqd똽ȕjf՟(<~>cD7}lW dވ,1]FƁ¼gh 3)v;Ais\J*NG_ĶwVRָ< o  ["@kFMS2_a?v-TBoʏ)=^):TqU5f%%wȯ ՟n浪AYP%q7LDtvQR ]t݉%1zr]hz]hpٌY{iջiuw ')1x ڴf ?\fl;%,<llOu)$iLՙ;ol_5wk⩙,H߮My}e^ֱXCSD R1 L>"^ ͪʷŧPm֙MB{5Ma:.UQ-YTtG1T 81it(Dqy\"yFM}յ1sB˲qo1f]#*͵G>BT}|S"kWgv rk(zNs*KFHs+זW`86yN(HWn$jSu^Q e[0ww_bh֩OGC4g'/? P&:(Y2>3mPN+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Y{<[l6`َq"Y[e9+Ұ+QI΁b9dxe4cy(!b.4sw@wlUm^{.H"cUL#hIJDt! r?oo~ն]!Dk HCZ{ޅAW=g!0X]ɮ9m蠡4F.'ً7&ĠqqaE32sHBU<|nBp;6 ^B4-gbI랑yQ7]$iwzĘWul~ P*5ۚ0-.F̼I͛3I>NxP QRQF:=.`CG41,'Ӄb[,Ԛ6W~^<<$eFMzҏ*ͶG2}%.u;ɂɃxԝpr<9Pg:4BҙPQJ>-nسc SlͯTyGS"<^RQN!Q}̟K<ƛ>=w?,~f2Q@urepTQ:fވVw2G k4琐Dz)?Ikz)!<j3g kF&1 W4mn)zV&a endstream endobj 37 0 obj << /Type /FontDescriptor /FontName /CWCFFB+CMR10 /Flags 4 /FontBBox [-251 -250 1009 969] /Ascent 694 /CapHeight 683 /Descent -194 /ItalicAngle 0 /StemV 69 /XHeight 431 /CharSet (/A/C/F/a/b/c/colon/comma/d/e/f/ff/ffi/g/h/hyphen/i/j/k/l/m/n/o/p/parenleft/parenright/period/q/r/s/slash/t/u/v/w/x/y/z) /FontFile 36 0 R >> endobj 38 0 obj << /Length1 793 /Length2 1564 /Length3 0 /Length 2113 /Filter /FlateDecode >> stream xڭ{Q/rE + ""ڄ#2{2Yw%Y/vÊr/(l[3$)}NGTŌ iF4?fVl'..ݴ($LZ/OSSh#Cm hoVt'& )fjb&e^m/PBOLZѠk6~S/tnbj6MndiR1?3 -$D~GGYggJRw}uq薾's-gnu&pr3R&q  }jZR!r:&󋁯ᕄguC!DQY;W(-0 % nܠj)dR6vxea~ZVȬFLe1 #}jE'0J +1hwŷ6w(lP VɦweLuK ϰͽ5EZV|.nak@p(COJq=+'9tζtheKIgH)6QlEI/㻇iyg/ A7'Cj,ttȈ/;%+wM6+;᝴o542ݍ+86i_U<sw(ks͔w_=,zlg8I6z}y2&BsYZR;D޶Jvo[r{6W$O]=GCr=u[]:aRs=Ʌ*(U(_>LM5|kUV^qm=&6tkVpM.< endstream endobj 39 0 obj << /Type /FontDescriptor /FontName /LSGOIB+CMTI10 /Flags 4 /FontBBox [-163 -250 1146 969] /Ascent 694 /CapHeight 683 /Descent -194 /ItalicAngle -14 /StemV 68 /XHeight 431 /CharSet (/a/c/l/s) /FontFile 38 0 R >> endobj 40 0 obj << /Length1 1434 /Length2 7948 /Length3 0 /Length 8788 /Filter /FlateDecode >> stream xڭeX RjnArK:QD:$EZZ>{W>_5a~^_s +-s ᰲ!VP'D ȺPLap']/'0@X4< .6V= :;tB< po-/x!PW4ms { E@:#;>MC'Wrvִr+ߓ?V.PgĿ=`.n^8@f !_4 P/>UrȺ;CJP_6 mV-SOֿfoF!2b60[=_H`[!pIB  "$ S>߄M8߄DqIZ !uMȜֿ $bێe "\\~g>?ÿ y#; >?Yw9| "])9RoD?!"uC\@Ak1 #U1 7Pٚbk8@H+Dvz2BHA>E>P?9 ?ٺoGF> un9 _@D o5U@|!68 a6!iMa9Q5{;qPK9Wꌮfl=bU:z>{mJct3xi@UkjSy ۘK(& oBFJulD>DɉǃñZ:H ,P.m0_7;JgP,*_.ǘQPKXTfTGϴ.\Xk{׋@sB;[%|b͕DNU*@Rsd7Z!\EiǂB)R'$+Nz5Ѣvޑw%`=|V0лyƞϺ)zMO>"} Bv/d^J1z.H$'4R̛OPm݅O\1\p%+\MUw(s_aT`7I,֫9Ns/vTAcbZ6w27"G]w:+QS;}O>J+0豪pviFBEfnR.栱˃ -oaX(L[:kdF1s^#%_1(:xZ0 &p z $FXV&YR㡱Lg%jZ0a|dQA6n hanK$mg %A&w) h'2g/bb;gKOk)8YP5Bϖ_+{.`y/: _9y۾xzIEP]VQ1`Q'@.nj30ĆrEY^\D޼ܥp+%3k) ^ *7%gX׿=,tbFSB&NN'硄rc2mѐE)6QQ;LgÚ_([5! a"5VGeՕ &R]%!NgS]=@utUӘ-4qs/;vuj8̟IYd|Tr DNǩ+$Ҕg$d<xhfJƝǵF)VQē,.N @54>gdJ\+߻382dh&[QdG0x $}вx0~"ukK 6jCj"6'\g[SY-QK=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9kr垉aj$|h듶9^B hhq}~YtOEQ1bJuV\LZGv^` UZt.,?Xe]L3LqJAX~OhzKAaqf/GkՖ軮a a+g4PR~fSj,ENu2cm$*xM\< A{3P}$C@]^< +/;"wNI"~$F a2a|B_GpR0"T'64Tfț^`w!'>ٻ|d+M# ܄9U #xA___U,6f)ف7=Τɮk'B`E5'9f8{Szǂi_MGOouV34gHؿl;BAP|ǻ=՞|9n'z-As4HѾp[+S*]aX wUǢA;>؉Mx?*2eiS8G~Iqt _@Uz< `P'8v!-i;ReWϊ%bd#$C&6z6_~}\O!/tD\r}$K 1Ei1"O۴=0;{1&[&|7AԌv%msLB;eE|=y[i>6gp.k/S yԷԻO魅_c3){hR;\u[\ ܘ&M]C|Ӭhe,d2ھy6oDD)hSД^mcYݰ: LqWa" "Psh෉ Ɨg&[*`vHV} ɷz_S::oWқj,=VYm\4XT̥OB~KW"6|>h(o2I4U,u\ ī TK3ш)Eqy{ΆplLKsq3*rtЫF4+7BWAJP# =V0bF!uAyR^:ٶ7Eug4 ]}{3QyAFw얅(|!{Xs:.'g#g`J :ԕCB}/-f :!2\/?Bc =Քp:yv%ח, C|aiY*?ELr ;52*!D4 M`KgajJQ<܌ɤR㻟H,b!1Ww (WNɒiR& > endobj 13 0 obj << /Type /Font /Subtype /Type1 /BaseFont /ENGSAK+CMB10 /FontDescriptor 31 0 R /FirstChar 111 /LastChar 122 /Widths 29 0 R >> endobj 15 0 obj << /Type /Font /Subtype /Type1 /BaseFont /ANYRFR+CMBX10 /FontDescriptor 33 0 R /FirstChar 67 /LastChar 120 /Widths 27 0 R >> endobj 14 0 obj << /Type /Font /Subtype /Type1 /BaseFont /RPYHCD+CMBX12 /FontDescriptor 35 0 R /FirstChar 97 /LastChar 114 /Widths 28 0 R >> endobj 17 0 obj << /Type /Font /Subtype /Type1 /BaseFont /CWCFFB+CMR10 /FontDescriptor 37 0 R /FirstChar 11 /LastChar 122 /Widths 25 0 R >> endobj 18 0 obj << /Type /Font /Subtype /Type1 /BaseFont /LSGOIB+CMTI10 /FontDescriptor 39 0 R /FirstChar 97 /LastChar 115 /Widths 24 0 R >> endobj 16 0 obj << /Type /Font /Subtype /Type1 /BaseFont /MPKPPA+CMTT10 /FontDescriptor 41 0 R /FirstChar 34 /LastChar 122 /Widths 26 0 R >> endobj 19 0 obj << /Type /Pages /Count 2 /Kids [8 0 R 21 0 R] >> endobj 42 0 obj << /Names [(Doc-Start) 12 0 R (page.1) 11 0 R (page.2) 23 0 R] /Limits [(Doc-Start) (page.2)] >> endobj 43 0 obj << /Dests 42 0 R >> endobj 44 0 obj << /Type /Catalog /Pages 19 0 R /Names 43 0 R /PageMode/UseOutlines /OpenAction 7 0 R >> endobj 45 0 obj << /Author(Firstname LastnameAffiliation)/Title(Title)/Subject()/Creator(LaTeX with hyperref package)/Producer(pdfTeX-1.40.3)/Keywords(---!!!---at least one keyword is required---!!!---) /CreationDate (D:20091119142603+01'00') /ModDate (D:20091119142603+01'00') /Trapped /False /PTEX.Fullbanner (This is pdfTeX using libpoppler, Version 3.141592-1.40.3-2.2 (Web2C 7.5.6) kpathsea version 3.5.6) >> endobj xref 0 46 0000000001 65535 f 0000000002 00000 f 0000000003 00000 f 0000000004 00000 f 0000000000 00000 f 0000000015 00000 n 0000003798 00000 n 0000006384 00000 n 0000009220 00000 n 0000009455 00000 n 0000006432 00000 n 0000009347 00000 n 0000009401 00000 n 0000045908 00000 n 0000046190 00000 n 0000046049 00000 n 0000046612 00000 n 0000046331 00000 n 0000046471 00000 n 0000046753 00000 n 0000011512 00000 n 0000011328 00000 n 0000009583 00000 n 0000011457 00000 n 0000011605 00000 n 0000011725 00000 n 0000012347 00000 n 0000012721 00000 n 0000013051 00000 n 0000013165 00000 n 0000013253 00000 n 0000015089 00000 n 0000015309 00000 n 0000021925 00000 n 0000022191 00000 n 0000024802 00000 n 0000025033 00000 n 0000033848 00000 n 0000034182 00000 n 0000036413 00000 n 0000036640 00000 n 0000045547 00000 n 0000046818 00000 n 0000046931 00000 n 0000046967 00000 n 0000047072 00000 n trailer << /Size 46 /Root 44 0 R /Info 45 0 R /ID [ ] >> startxref 47486 %%EOF zoo/vignettes/zoo-refcard-raw.tex0000644000175400001440000001054211747047642017026 0ustar zeileisusers\begin{tabular}{rp{9cm}} \multicolumn{2}{l}{\textbf{Creation}} \\ \code{zoo(x, order.by)} & creation of a \code{"zoo"} object from the observations \code{x} (a vector or a matrix) and an index \code{order.by} by which the observations are ordered. \\ & For computations on arbitrary index classes, methods to the following generic functions are assumed to work: combining \code{c()}, querying length \code{length()}, subsetting \code{[}, ordering \code{ORDER()} and value matching \code{MATCH()}. For pretty printing an \code{as.character} and/or \code{index2char} method might be helpful.\\[0.5cm] \multicolumn{2}{l}{\textbf{Creation of regular series}} \\ \code{zoo(x, order.by, freq)} & works as above but creates a \code{"zooreg"} object which inherits from \code{"zoo"} if the frequency \code{freq} complies with the index \code{order.by}. An \code{as.numeric} method has to be available for the index class.\\ \code{zooreg(x, start, end, freq)} & creates a \code{"zooreg"} series with a numeric index as above and has (almost) the same interface as \code{ts()}.\\[0.5cm] \multicolumn{2}{l}{\textbf{Standard methods}} \\ \code{plot} & plotting \\ \code{lines} & adding a \code{"zoo"} series to a plot \\ \code{print} & printing \\ \code{summary} & summarizing (column-wise) \\ \code{str} & displaying structure of \code{"zoo"} objects \\ \code{head}, \code{tail} & head and tail of \code{"zoo"} objects \\[0.5cm] \multicolumn{2}{l}{\textbf{Coercion}} \\ \code{as.zoo} & coercion to \code{"zoo"} is available for objects of class \code{"ts"}, \code{"its"}, \code{"irts"} (plus a default method).\\ \code{as.}\textit{class}\code{.zoo} & coercion from \code{"zoo"} to other classes. Currently available for \textit{class} in \code{"matrix"}, \code{"vector"}, \code{"data.frame"}, \code{"list"}, \code{"irts"}, \code{"its"} and \code{"ts"}. \\ \code{is.zoo} & querying wether an object is of class \code{"zoo"} \\[0.5cm] \multicolumn{2}{l}{\textbf{Merging and binding}} \\ \code{merge} & union, intersection, left join, right join along indexes\\ \code{cbind} & column binding along the intersection of the index\\ \code{c}, \code{rbind} & combining/row binding (indexes may not overlap)\\ \code{aggregate} & compute summary statistics along a coarser grid of indexes \\[0.5cm] \multicolumn{2}{l}{\textbf{Mathematical operations}} \\ \code{Ops} & group generic functions performed along the intersection of indexes\\ \code{t} & transposing (coerces to \code{"matrix"} before) \\ \code{cumsum} & compute (columnwise) cumulative quantities: sums \code{cumsum()}, products \code{cumprod()}, maximum \code{cummax()}, minimum \code{cummin()}.\\[0.5cm] \end{tabular} \newpage \begin{tabular}{rp{9cm}} \multicolumn{2}{l}{\textbf{Extracting and replacing data and index}} \\ \code{index, time} & extract the index of a series\\ \code{index<-}, \code{time<-} & replace the index of a series\\ \code{coredata}, \code{coredata<-} & extract and replace the data associated with a \code{"zoo"} object\\ \code{lag} & lagged observations \\ \code{diff} & arithmetic and geometric differences \\ \code{start, end} & querying start and end of a series \\ \code{window, window<-} & subsetting of \code{"zoo"} objects using their index\\[0.5cm] \multicolumn{2}{l}{\textbf{\code{NA} handling}} \\ \code{na.omit} & omit \code{NA}s \\ \code{na.contiguous} & compute longest sequence of non-\code{NA} observations \\ \code{na.locf} & impute \code{NA}s by carrying forward the last observation\\ \code{na.approx} & impute \code{NA}s by interpolation\\[0.5cm] \code{na.trim} & remove leading and/or trailing \code{NA}s\\[0.5cm] \multicolumn{2}{l}{\textbf{Rolling functions}} \\ \code{rollapply} & apply a function to rolling margin of an array \\ \code{rollmean} & more efficient functions for computing the rolling mean, median and maximum are \code{rollmean()}, \code{rollmedian()} and \code{rollmax()}, respectively\\[0.5cm] \multicolumn{2}{l}{\textbf{Methods for regular series}} \\ \code{is.regular} & checks whether a series is weakly (or strictly if \code{strict = TRUE}) regular \\ \code{frequency}, \code{deltat} & extracts the frequency or its reciprocal value respectively from a series, for \code{"zoo"} series the functions try to determine the regularity and frequency in a data-driven way\\ \code{cycle} & gives the position in the cycle of a regular series \\[0.5cm] \end{tabular} zoo/vignettes/zoo-read.Rnw0000644000175400001440000004334011747047642015514 0ustar zeileisusers\documentclass[article,nojss]{jss} \DeclareGraphicsExtensions{.pdf,.eps} \newcommand{\mysection}[1]{\subsubsection[#1]{\textbf{#1}}} %% need no \usepackage{Sweave} \newcommand{\fct}[1]{{\code{#1()}}} \newcommand{\class}[1]{{`\code{#1}'}} \SweaveOpts{engine = R, strip.white = true, keep.source = true, eps = false} \author{ Gabor Grothendieck\\GKX Associates Inc. \And Achim Zeileis\\Universit\"at Innsbruck} \Plainauthor{Gabor Grothendieck, Achim Zeileis} \title{Reading Data in \pkg{zoo}} \Plaintitle{Reading Data in zoo} \Keywords{irregular time series, daily data, weekly data, data frame, text file} \Abstract{ This vignette gives examples of how to read data in various formats in the \pkg{zoo} package using the \fct{read.zoo} function. The function \fct{read.zoo} function expects either a text file (or more generally a text connection) as input or a data frame (and the former case is handled by first using \fct{read.table} to produce the data frame). Subsequently, \fct{read.zoo} provides a wide collection of convenience functionality to turn that data frame into a \class{zoo} series with a specific structure and a specific time index. In this vignette, an overview is provided of the wide variety of cases that can be handled with \fct{read.zoo}. All examples assume that \pkg{zoo} is already loaded and (if necessary) that the \pkg{chron} package has been loaded as well. } \Address{ Gabor Grothendieck\\ GKX Associates Inc.\\ E-mail: \email{ggrothendieck@gmail.com}\\ Achim Zeileis\\ Universit\"at Innsbruck\\ E-mail: \email{Achim.Zeileis@R-project.org}\\ } \begin{document} \SweaveOpts{engine=R,eps=FALSE} %\VignetteIndexEntry{Reading Data in zoo} %\VignetteDepends{zoo} %\VignetteKeywords{irregular time series, daily data, weekly data, data frame, text file} %\VignettePackage{zoo} <>= library("zoo") library("chron") Sys.setenv(TZ = "GMT") @ \section*{Example 1} \textbf{Input class:} Text file/connection (space-separated with header). \textbf{Input index:} \class{integer}. \textbf{Output class:} Multivariate \class{zoo} series. \textbf{Output index:} \class{integer}. \textbf{Strategy:} No transformation of time tindex needed, hence only a simple call to \fct{read.zoo}. <>= Lines <- " time latitude longitude altitude distance heartrate 1277648884 0.304048 -0.793819 260 0.000000 94 1277648885 0.304056 -0.793772 262 4.307615 95 1277648894 0.304075 -0.793544 263 25.237911 103 1277648902 0.304064 -0.793387 256 40.042988 115 " z <- read.zoo(textConnection(Lines), header = TRUE) z @ \newpage \section*{Example 2} \textbf{Input class:} \class{data.frame}. \textbf{Input index:} \class{factor} with labels indicating AM/PM times but no date. \textbf{Output class:} Multivariate \class{zoo} series. \textbf{Output index:} \class{times} (from \pkg{chron}). \textbf{Strategy:} The idea is to add some dummy date (here 1970-01-01) to the \class{character} lables, then transform to \class{chron} and extract the \class{times}. <>= DF <- structure(list( Time = structure(1:5, .Label = c("7:10:03 AM", "7:10:36 AM", "7:11:07 AM", "7:11:48 AM", "7:12:25 AM"), class = "factor"), Bid = c(6118.5, 6118.5, 6119.5, 6119, 6119), Offer = c(6119.5, 6119.5, 6119.5, 6120, 6119.5)), .Names = c("Time", "Bid", "Offer"), row.names = c(NA, -5L), class = "data.frame") DF @ <>= z <- read.zoo(DF, FUN = function(x) times(as.chron(paste("1970-01-01", x), format = "%Y-%m-%d %H:%M:%S %p"))) z @ \newpage \section*{Example 3} \textbf{Input class:} Text file/connection (semicolon-separated with header). \textbf{Input index:} \class{factor}s with labels indicating dates (column~1) and times (column~2). \textbf{Output class:} Multivariate \class{zoo} series, with separate columns for each date. \textbf{Output index:} \class{times} (from \pkg{chron}). \textbf{Strategy:} Split the data based on date (column~1) and process times (column~2) to \class{times}. Enhance column names at the end. <>= Lines <- " Date;Time;Close 01/09/2009;10:00;56567 01/09/2009;10:05;56463 01/09/2009;10:10;56370 01/09/2009;16:45;55771 01/09/2009;16:50;55823 01/09/2009;16:55;55814 02/09/2009;10:00;55626 02/09/2009;10:05;55723 02/09/2009;10:10;55659 02/09/2009;16:45;55742 02/09/2009;16:50;55717 02/09/2009;16:55;55385 " f <- function(x) times(paste(x, 0, sep = ":")) z <- read.zoo(textConnection(Lines), header = TRUE, sep = ";", split = 1, index = 2, FUN = f) colnames(z) <- sub("X(..).(..).(....)", "\\3-\\2-\\1", colnames(z)) z @ \newpage \section*{Example 4} \textbf{Input class:} Text file/connection (space-separated with header). \textbf{Input index:} \class{factor}s with labels indicating dates (column~1) and times (column~2). \textbf{Output class:} Multivariate \class{zoo} series. \textbf{Output index:} \class{chron} (from \pkg{chron}). \textbf{Strategy:} Indicate vector of two columns in \code{index}, which is subsequently processed by a \code{FUN} taking two arguments and returning a \class{chron} time/date. <>= Lines <- " Date Time O H L C 1/2/2005 17:05 1.3546 1.3553 1.3546 1.35495 1/2/2005 17:10 1.3553 1.3556 1.3549 1.35525 1/2/2005 17:15 1.3556 1.35565 1.35515 1.3553 1/2/2005 17:25 1.355 1.3556 1.355 1.3555 1/2/2005 17:30 1.3556 1.3564 1.35535 1.3563 " f <- function(d, t) as.chron(paste(as.Date(chron(d)), t)) z <- read.zoo(textConnection(Lines), header = TRUE, index = 1:2, FUN = f) z @ \newpage \section*{Example 5} \textbf{Input class:} Text file/connection (space-separated with non-matching header). \textbf{Input index:} \class{factor}s with labels indicating dates (column~6) and unneeded weekdays (column~5) and times (column~7). \textbf{Output class:} Multivariate \class{zoo} series. \textbf{Output index:} \class{Date}. \textbf{Strategy:} First, \code{skip} the header line, remove unneeded columns by setting \code{colClasses} to \code{"NULL"}, and set suitable \code{col.names}. Second, convert the date column to a \class{Date} index using \code{format}. Finally, aggregate over duplicate dates, keeping only the last observation. <>= Lines <- " views number timestamp day time 1 views 910401 1246192687 Sun 6/28/2009 12:38 2 views 921537 1246278917 Mon 6/29/2009 12:35 3 views 934280 1246365403 Tue 6/30/2009 12:36 4 views 986463 1246888699 Mon 7/6/2009 13:58 5 views 995002 1246970243 Tue 7/7/2009 12:37 6 views 1005211 1247079398 Wed 7/8/2009 18:56 7 views 1011144 1247135553 Thu 7/9/2009 10:32 8 views 1026765 1247308591 Sat 7/11/2009 10:36 9 views 1036856 1247436951 Sun 7/12/2009 22:15 10 views 1040909 1247481564 Mon 7/13/2009 10:39 11 views 1057337 1247568387 Tue 7/14/2009 10:46 12 views 1066999 1247665787 Wed 7/15/2009 13:49 13 views 1077726 1247778752 Thu 7/16/2009 21:12 14 views 1083059 1247845413 Fri 7/17/2009 15:43 15 views 1083059 1247845824 Fri 7/17/2009 18:45 16 views 1089529 1247914194 Sat 7/18/2009 10:49 " cl <- c("NULL", "numeric", "character")[c(1, 1, 2, 2, 1, 3, 1)] cn <- c(NA, NA, "views", "number", NA, NA, NA) z <- read.zoo(textConnection(Lines), skip = 1, col.names = cn, colClasses = cl, index = 3, format = "%m/%d/%Y", aggregate = function(x) tail(x, 1)) z @ Extract all Thursdays and Fridays. <>= (z45 <- z[format(time(z), "%w") %in% 4:5,]) @ Keep last entry in each week. <>= z45[!duplicated(format(time(z45), "%U"), fromLast = TRUE), ] @ Alternative approach: Above approach labels each point as it was originally labeled, i.e., if Thursday is used it gets the date of that Thursday. Another approach is to always label the resulting point as Friday and also use the last available value even if its not Thursday. Create daily grid and fill in so Friday is filled in with prior value if Friday is \code{NA}. <>= g <- seq(start(z), end(z), by = "day") z.filled <- na.locf(z, xout = g) @ Extract Fridays, including those filled in from previous day. <>= z.filled[format(time(z.filled), "%w") == "5", ] @ \newpage \section*{Example 6} \textbf{Input class:} Text file/connection (comma-separated with header). \textbf{Input index:} \class{factor}s with labels indicating dates (column~1) and times (column~2). \textbf{Output class:} Multivariate \class{zoo} series. \textbf{Output index:} \class{chron} (from \pkg{chron}) or \class{POSIXct}. \textbf{Strategy:} Three versions, all using vector \code{index = 1:2}. <>= Lines <- " Date,Time,Open,High,Low,Close,Up,Down 05.02.2001,00:30,421.20,421.20,421.20,421.20,11,0 05.02.2001,01:30,421.20,421.40,421.20,421.40,7,0 05.02.2001,02:00,421.30,421.30,421.30,421.30,0,5" @ With custom \code{FUN} using \fct{chron} after appending seconds. <>= f <- function(d, t) chron(d, paste(t, "00", sep = ":"), format = c("m.d.y", "h:m:s")) z <- read.zoo(textConnection(Lines), sep = ",", header = TRUE, index = 1:2, FUN = f) z @ With custom \code{FUN} using \fct{as.chron} with suitable \code{format}. <>= f2 <- function(d, t) as.chron(paste(d, t), format = "%d.%m.%Y %H:%M") z2 <- read.zoo(textConnection(Lines), sep = ",", header = TRUE, index = 1:2, FUN = f2) z2 @ Without \code{FUN}, hence the \code{index} columns are pasted together and then passt do \fct{as.POSIXct} because \code{tz} and \code{format} are specified. <>= z3 <- read.zoo(textConnection(Lines), sep = ",", header = TRUE, index = 1:2, tz = "", format = "%d.%m.%Y %H:%M") z3 @ \newpage \section*{Example 7} \textbf{Input class:} Text file/connection (space-separated with header). \textbf{Input index:} \class{factor}s with labels indicating dates (column~1) and times (column~2). \textbf{Output class:} Multivariate \class{zoo} series. \textbf{Output index:} \class{POSIXct}. \textbf{Strategy:} Due to standard date/time formats, only \code{index = 1:2} and \code{tz = ""} need to be specified to produce \class{POSIXct} index. <>= Lines <- "Date Time V2 V3 V4 V5 2010-10-15 13:43:54 73.8 73.8 73.8 73.8 2010-10-15 13:44:15 73.8 73.8 73.8 73.8 2010-10-15 13:45:51 73.8 73.8 73.8 73.8 2010-10-15 13:46:21 73.8 73.8 73.8 73.8 2010-10-15 13:47:27 73.8 73.8 73.8 73.8 2010-10-15 13:47:54 73.8 73.8 73.8 73.8 2010-10-15 13:49:51 73.7 73.7 73.7 73.7 " z <- read.zoo(textConnection(Lines), header = TRUE, index = 1:2, tz = "") z @ \newpage \section*{Example 8} \textbf{Input class:} Text file/connection (space-separated without header). \textbf{Input index:} \class{factor} with labels indicating dates. \textbf{Output class:} Multivariate \class{zoo} series, with separate columns depending on column~2. \textbf{Output index:} \class{Date}. \textbf{Strategy:} Non-standard \code{na.strings} format needs to be specified, series is \code{split} based on second column, and date \code{format} (in column~1, default) needs to be specified. <>= Lines <- " 13/10/2010 A 23 13/10/2010 B 12 13/10/2010 C 124 14/10/2010 A 43 14/10/2010 B 54 14/10/2010 C 65 15/10/2010 A 43 15/10/2010 B N.A. 15/10/2010 C 65 " z <- read.zoo(textConnection(Lines), na.strings = "N.A.", format = "%d/%m/%Y", split = 2) z @ \newpage \section*{Example 9} \textbf{Input class:} Text file/connection (comma-separated with header). \textbf{Input index:} \class{factor} with labels indicating date/time. \textbf{Output class:} Univariate \class{zoo} series. \textbf{Output index:} \class{chron} (from \pkg{chron}) or \class{POSIXct}. \textbf{Strategy:} Ignore first two columns by setting \code{colClasses} to \code{"NULL"}. Either produce \class{chron} index via \fct{as.chron} or use all defaults to produce \class{POSIXct} by setting \code{tz}. <>= Lines <- ' "","Fish_ID","Date","R2sqrt" "1",1646,2006-08-18 08:48:59,0 "2",1646,2006-08-18 09:53:20,100 ' z <- read.zoo(textConnection(Lines), header = TRUE, sep = ",", colClasses = c("NULL", "NULL", "character", "numeric"), FUN = as.chron) z z2 <- read.zoo(textConnection(Lines), header = TRUE, sep = ",", colClasses = c("NULL", "NULL", "character", "numeric"), tz = "") z2 @ \newpage \section*{Example 10} \textbf{Input class:} Text file/connection (space-separated with non-matching header). \textbf{Input index:} \class{factor} with labels indicating date (column~3) and time (column~4). \textbf{Output class:} Multivariate \class{zoo} series. \textbf{Output index:} \class{chron} (from \pkg{chron}) or \class{POSIXct}. \textbf{Strategy:} \code{skip} non-matching header and extract date/time from two columns \code{index = 3:4}. Either using sequence of two functions \code{FUN} and \code{FUN2} or employ defaults yielding \class{POSIXct}. <>= Lines <- " iteration Datetime VIC1 NSW1 SA1 QLD1 1 1 2011-01-01 00:30 5482.09 7670.81 2316.22 5465.13 2 1 2011-01-01 01:00 5178.33 7474.04 2130.30 5218.61 3 1 2011-01-01 01:30 4975.51 7163.73 2042.39 5058.19 4 1 2011-01-01 02:00 5295.36 6850.14 1940.19 4897.96 5 1 2011-01-01 02:30 5042.64 6587.94 1836.19 4749.05 6 1 2011-01-01 03:00 4799.89 6388.51 1786.32 4672.92 " z <- read.zoo(textConnection(Lines), skip = 1, index = 3:4, FUN = paste, FUN2 = as.chron) z z2 <- read.zoo(textConnection(Lines), skip = 1, index = 3:4, tz = "") z2 @ \newpage \section*{Example 11} \textbf{Input class:} \class{data.frame}. \textbf{Input index:} \class{Date}. \textbf{Output class:} Multivariate \class{zoo} series. \textbf{Output index:} \class{Date}. \textbf{Strategy:} Given a \class{data.frame} only keep last row in each month. Use \fct{read.zoo} to convert to \class{zoo} and then \fct{na.locf} and \fct{duplicated}. <>= DF <- structure(list( Date = structure(c(14609, 14638, 14640, 14666, 14668, 14699, 14729, 14757, 14759, 14760), class = "Date"), A = c(4.9, 5.1, 5, 4.8, 4.7, 5.3, 5.2, 5.4, NA, 4.6), B = c(18.4, 17.7, NA, NA, 18.3, 19.4, 19.7, NA, NA, 18.1), C = c(32.6, NA, 32.8, NA, 33.7, 32.4, 33.6, NA, 34.5, NA), D = c(77, NA, 78.7, NA, 79, 77.8, 79, 81.7, NA, NA)), .Names = c("Date", "A", "B", "C", "D"), row.names = c(NA, -10L), class = "data.frame") DF z <- read.zoo(DF) na.locf(z)[!duplicated(as.yearmon(time(z)), fromLast = TRUE)] @ \newpage \section*{Example 12} \textbf{Input class:} Text file/connection (space-separated without header). \textbf{Input index:} \class{factor} with labels indicating dates. \textbf{Output class:} Univariate \class{zoo} series. \textbf{Output index:} \class{Date}. \textbf{Strategy:} Only keep last point in case of duplicate dates. <>= Lines <- " 2009-10-07 0.009378 2009-10-19 0.014790 2009-10-23 -0.005946 2009-10-23 0.009096 2009-11-08 0.004189 2009-11-10 -0.004592 2009-11-17 0.009397 2009-11-24 0.003411 2009-12-02 0.003300 2010-01-15 0.010873 2010-01-20 0.010712 2010-01-20 0.022237 " z <- read.zoo(textConnection(Lines), aggregate = function(x) tail(x, 1)) z @ \newpage \section*{Example 13} \textbf{Input class:} Text file/connection (comma-separated with header). \textbf{Input index:} \class{factor} with labels indicating date/time. \textbf{Output class:} Multivariate \class{zoo} series. \textbf{Output index:} \class{POSIXct} or \class{chron} (from \pkg{chron}). \textbf{Strategy:} Dates and times are in standard format, hence the default \class{POSIXct} can be produced by setting \code{tz} or, alternatively, \class{chron} can be produced by setting \fct{as.chron} as \code{FUN}. <>= Lines <- " timestamp,time-step-index,value 2009-11-23 15:58:21,23301,800 2009-11-23 15:58:29,23309,950 " z <- read.zoo(textConnection(Lines), header = TRUE, sep = ",", tz = "") z z2 <- read.zoo(textConnection(Lines), header = TRUE, sep = ",", FUN = as.chron) z2 @ \newpage \section*{Example 14} \textbf{Input class:} Text file/connection (space-separated with header). \textbf{Input index:} \class{factor}s with labels indicating dates (column~1) times (column~2). \textbf{Output class:} Univariate \class{zoo} series. \textbf{Output index:} \class{chron} (from \pkg{chron}). \textbf{Strategy:} Indicate vector \code{index = 1:2} and use \fct{chron} (which takes two separate arguments for dates and times) to produce \class{chron} index. <>= Lines <- " Date Time Value 01/23/2000 10:12:15 12.12 01/24/2000 11:10:00 15.00 " z <- read.zoo(textConnection(Lines), header = TRUE, index = 1:2, FUN = chron) z @ \newpage \section*{Example 15} \textbf{Input class:} Text file/connection (space-separated with header). \textbf{Input index:} \class{numeric} year with quarters represented by separate columns. \textbf{Output class:} Univariate \class{zoo} series. \textbf{Output index:} \class{yearqtr}. \textbf{Strategy:} First, create a multivariate annual time series using the year index. Then, create a regular univariate quarterly series by collapsing the annual series to a vector and adding a new \class{yearqtr} index from scratch. <>= Lines <- " Year Qtr1 Qtr2 Qtr3 Qtr4 1992 566 443 329 341 1993 344 212 133 112 1994 252 252 199 207 " za <- read.zoo(textConnection(Lines), header = TRUE) za zq <- zooreg(as.vector(t(za)), start = yearqtr(start(za)), freq = 4) zq @ \newpage \section{Further comments} Multiple files can be read and subsequently merged. <>= filenames <- dir(pattern = "csv$") z <- read.zoo(filenames, header = TRUE, sep = ",", fixed = FALSE) @ \end{document} zoo/vignettes/zoo-quickref.Rnw0000644000175400001440000002771411747047642016421 0ustar zeileisusers\documentclass[article,nojss]{jss} \DeclareGraphicsExtensions{.pdf,.eps} \newcommand{\mysection}[1]{\subsubsection[#1]{\textbf{#1}}} %% need no \usepackage{Sweave} \author{Ajay Shah\\National Institute of Public\\Finance and Policy, India \And Achim Zeileis\\Universit\"at Innsbruck \And Gabor Grothendieck\\GKX Associates Inc.} \Plainauthor{Ajay Shah, Achim Zeileis, Gabor Grothendieck} \title{\pkg{zoo} Quick Reference} \Plaintitle{zoo Quick Reference} \Keywords{irregular time series, daily data, weekly data, returns} \Abstract{ This vignette gives a brief overview of (some of) the functionality contained in \pkg{zoo} including several nifty code snippets when dealing with (daily) financial data. For a more complete overview of the package's functionality and extensibility see \cite{zoo:Zeileis+Grothendieck:2005} (contained as vignette ``zoo'' in the package), the manual pages and the reference card. } \Address{ Ajay Shah\\ National Institute of Public Finance and Policy, India\\ E-mail: \email{ajayshah@mayin.org}\\ Achim Zeileis\\ Universit\"at Innsbruck\\ E-mail: \email{Achim.Zeileis@R-project.org}\\ Gabor Grothendieck\\ GKX Associates Inc.\\ E-mail: \email{ggrothendieck@gmail.com} } \begin{document} \SweaveOpts{engine=R,eps=FALSE} %\VignetteIndexEntry{zoo Quick Reference} %\VignetteDepends{zoo,tseries} %\VignetteKeywords{irregular time series, daily data, weekly data, returns} %\VignettePackage{zoo} <>= library("zoo") library("tseries") online <- FALSE ## if set to FALSE the local copy of ## is used instead of get.hist.quote() options(prompt = "R> ") Sys.setenv(TZ = "GMT") @ \mysection{Read a series from a text file} To read in data in a text file, \code{read.table()} and associated functions can be used as usual with \code{zoo()} being called subsequently. The convenience function \code{read.zoo} is a simple wrapper to these functions that assumes the index is in the first column of the file and the remaining columns are data. Data in \code{demo1.txt}, where each row looks like \begin{verbatim} 23 Feb 2005|43.72 \end{verbatim} can be read in via <>= inrusd <- read.zoo("demo1.txt", sep = "|", format="%d %b %Y") @ The \code{format} argument causes the first column to be transformed to an index of class \code{"Date"}. The data in \code{demo2.txt} look like \begin{verbatim} Daily,24 Feb 2005,2055.30,4337.00 \end{verbatim} and requires more attention because of the format of the first column. <>= tmp <- read.table("demo2.txt", sep = ",") z <- zoo(tmp[, 3:4], as.Date(as.character(tmp[, 2]), format="%d %b %Y")) colnames(z) <- c("Nifty", "Junior") @ \mysection{Query dates} To return all dates corresponding to a series \code{index(z)} or equivalently <>= time(z) @ can be used. The first and last date can be obtained by <>= start(z) end(inrusd) @ \mysection{Convert back into a plain matrix} To strip off the dates and just return a plain vector/matrix \code{coredata} can be used <>= plain <- coredata(z) str(plain) @ \mysection{Union and intersection} Unions and intersections of series can be computed by \code{merge}. The intersection are those days where both series have time points: <>= m <- merge(inrusd, z, all = FALSE) @ whereas the union uses all dates and fills the gaps where one series has a time point but the other does not with \code{NA}s (by default): <>= m <- merge(inrusd, z) @ \code{cbind(inrusd, z)} is almost equivalent to the \code{merge} call, but may lead to inferior naming in some situations hence \code{merge} is preferred To combine a series with its lag, use <>= merge(inrusd, lag(inrusd, -1)) @ \mysection{Visualization} By default, the \code{plot} method generates a graph for each series in \code{m} \begin{center} \setkeys{Gin}{width=0.7\textwidth} <>= plot(m) @ \end{center} but several series can also be plotted in a single window. \begin{center} \setkeys{Gin}{width=0.7\textwidth} <>= plot(m[, 2:3], plot.type = "single", col = c("red", "blue"), lwd = 2) @ \end{center} \mysection{Select (a few) observations} Selections can be made for a range of dates of interest <>= m[as.Date("2005-03-10")] @ \mysection{Handle missing data} Various methods for dealing with \code{NA}s are available, including linear interpolation <>= interpolated <- na.approx(m) @ `last observation carried forward', <>= m <- na.locf(m) m @ and others. \mysection{Prices and returns} To compute log-difference returns in \%, the following convenience function is defined <>= prices2returns <- function(x) 100*diff(log(x)) @ which can be used to convert all columns (of prices) into returns. <>= r <- prices2returns(m) @ A 10-day rolling window standard deviations (for all columns) can be computed by <>= rollapply(r, 10, sd) @ To go from a daily series to the series of just the last-traded-day of each month \code{aggregate} can be used <>= prices2returns(aggregate(m, as.yearmon, tail, 1)) @ Analogously, the series can be aggregated to the last-traded-day of each week employing a convenience function \code{nextfri} that computes for each \code{"Date"} the next friday. <>= nextfri <- function(x) 7 * ceiling(as.numeric(x-5+4) / 7) + as.Date(5-4) prices2returns(aggregate(na.locf(m), nextfri, tail, 1)) @ Here is a similar example of \code{aggregate} where we define \code{to4sec} analogously to \code{nextfri} in order to aggregate the \code{zoo} object \code{zsec} every 4 seconds. <>= zsec <- structure(1:10, index = structure(c(1234760403.968, 1234760403.969, 1234760403.969, 1234760405.029, 1234760405.029, 1234760405.03, 1234760405.03, 1234760405.072, 1234760405.073, 1234760405.073 ), class = c("POSIXt", "POSIXct"), tzone = ""), class = "zoo") to4sec <- function(x) as.POSIXct(4*ceiling(as.numeric(x)/4), origin = "1970-01-01") aggregate(zsec, to4sec, tail, 1) @ Here is another example using the same \code{zsec} zoo object but this time rather than aggregating we truncate times to the second using the last data value for each such second. For large objects this will be much faster than using \code{aggregate.zoo} . <>= # tmp is zsec with time discretized into one second bins tmp <- zsec st <- start(tmp) Epoch <- st - as.numeric(st) time(tmp) <- as.integer(time(tmp) + 1e-7) + Epoch # find index of last value in each one second interval ix <- !duplicated(time(tmp), fromLast = TRUE) # merge with grid merge(tmp[ix], zoo(, seq(start(tmp), end(tmp), "sec"))) # Here is a function which generalizes the above: intraday.discretise <- function(b, Nsec) { st <- start(b) time(b) <- Nsec * as.integer(time(b)+1e-7) %/% Nsec + st - as.numeric(st) ix <- !duplicated(time(b), fromLast = TRUE) merge(b[ix], zoo(, seq(start(b), end(b), paste(Nsec, "sec")))) } intraday.discretise(zsec, 1) @ \mysection{Query Yahoo! Finance} When connected to the internet, Yahoo! Finance can be easily queried using the \code{get.hist.quote} function in <>= library("tseries") @ <>= if(online) { sunw <- get.hist.quote(instrument = "SUNW", start = "2004-01-01", end = "2004-12-31") sunw2 <- get.hist.quote(instrument = "SUNW", start = "2004-01-01", end = "2004-12-31", compression = "m", quote = "Close") eur.usd <- get.hist.quote(instrument = "EUR/USD", provider = "oanda", start = "2004-01-01", end = "2004-12-31") save(sunw, sunw2, eur.usd, file = "sunw.rda") } else { load("sunw.rda") } @ From version 0.9-30 on, \code{get.hist.quote} by default returns \verb/"zoo"/ series with a \verb/"Date"/ attribute (in previous versions these had to be transformed from \verb/"ts"/ `by hand'). A daily series can be obtained by: <>= sunw <- get.hist.quote(instrument = "SUNW", start = "2004-01-01", end = "2004-12-31") @ A monthly series can be obtained and transformed by <>= sunw2 <- get.hist.quote(instrument = "SUNW", start = "2004-01-01", end = "2004-12-31", compression = "m", quote = "Close") @ Here, \verb/"yearmon"/ dates might be even more useful: <>= time(sunw2) <- as.yearmon(time(sunw2)) @ The same series can equivalently be computed from the daily series via <>= sunw3 <- aggregate(sunw[, "Close"], as.yearmon, tail, 1) @ The corresponding returns can be computed via <>= r <- prices2returns(sunw3) @ where \code{r} is still a \verb/"zoo"/ series. \mysection{Query Oanda} Similarly you can obtain historical exchange rates from \url{http://www.oanda.com/} using \code{get.hist.quote}. A daily series of EUR/USD exchange rates can be queried by <>= eur.usd <- get.hist.quote(instrument = "EUR/USD", provider = "oanda", start = "2004-01-01", end = "2004-12-31") @ This contains the exchange rates for every day in 2004. However, it is common practice in many situations to exclude the observations from weekends. To do so, we write a little convenience function which can determine for a vector of \code{"Date"} observations whether it is a weekend or not <>= is.weekend <- function(x) ((as.numeric(x)-2) %% 7) < 2 @ Based on this we can omit all observations from weekends <>= eur.usd <- eur.usd[!is.weekend(time(eur.usd))] @ The function \code{is.weekend} introduced above exploits the fact that a \code{"Date"} is essentially the number of days since 1970-01-01, a Thursday. A more intelligible function which yields identical results could be based on the \code{"POSIXlt"} class <>= is.weekend <- function(x) { x <- as.POSIXlt(x) x$wday > 5 | x$wday < 1 } @ \mysection{Summaries} Here we create a daily series and then find the series of quarterly means and standard deviations and also for weekly means and standard deviations where we define weeks to end on Tuesay. We do the above separately for mean and standard deviation, binding the two results together and then show a different approach in which we define a custom \code{ag} function that can accept multiple function names as a vector argument. <>= date1 <- seq(as.Date("2001-01-01"), as.Date("2002-12-1"), by = "day") len1 <- length(date1) set.seed(1) # to make it reproducible data1 <- zoo(rnorm(len1), date1) # quarterly summary data1q.mean <- aggregate(data1, as.yearqtr, mean) data1q.sd <- aggregate(data1, as.yearqtr, sd) head(cbind(mean = data1q.mean, sd = data1q.sd), main = "Quarterly") # weekly summary - week ends on tuesday # Given a date find the next Tuesday. # Based on formula in Prices and Returns section. nexttue <- function(x) 7 * ceiling(as.numeric(x - 2 + 4)/7) + as.Date(2 - 4) data1w <- cbind( mean = aggregate(data1, nexttue, mean), sd = aggregate(data1, nexttue, sd) ) head(data1w) ### ALTERNATIVE ### # Create function ag like aggregate but takes vector of # function names. FUNs <- c(mean, sd) ag <- function(z, by, FUNs) { f <- function(f) aggregate(z, by, f) do.call(cbind, sapply(FUNs, f, simplify = FALSE)) } data1q <- ag(data1, as.yearqtr, c("mean", "sd")) data1w <- ag(data1, nexttue, c("mean", "sd")) head(data1q) head(data1w) @ \bibliography{zoo} \end{document} zoo/vignettes/zoo-faq.Rnw0000644000175400001440000007010712067427347015351 0ustar zeileisusers\documentclass[article,nojss]{jss} \DeclareGraphicsExtensions{.pdf,.eps} %%\newcommand{\mysection}[2]{\subsubsection[#2]{\textbf{#1}}} \let\mysection=\subsubsection \renewcommand{\jsssubsubsec}[2][default]{\vskip \preSskip% \pdfbookmark[3]{#1}{Subsubsection.\thesubsubsection.#1}% \refstepcounter{subsubsection}% {\large \textbf{\textit{#2}}} \nopagebreak \vskip \postSskip \nopagebreak} %% need no \usepackage{Sweave} \author{\pkg{zoo} Development Team} \Plainauthor{zoo Development Team} \Address{ \pkg{zoo} Development Team\\ \proglang{R}-Forge: \url{http://R-Forge.R-project.org/projects/zoo/}\\ Comprehensive \proglang{R} Archive Network: \url{http://CRAN.R-project.org/package=zoo} } \title{\pkg{zoo} FAQ} \Plaintitle{zoo FAQ} \Keywords{irregular time series, ordered observations, time index, daily data, weekly data, returns} \Abstract{ This is a collection of frequently asked questions (FAQ) about the \pkg{zoo} package together with their answers. } \begin{document} \SweaveOpts{engine=R,eps=FALSE} %\VignetteIndexEntry{zoo FAQ} %\VignetteDepends{zoo,chron,timeDate,timeSeries} %\VignetteKeywords{irregular time series, ordered observations, time index, daily data, weekly data, returns} %\VignettePackage{zoo} <>= library("zoo") Sys.setenv(TZ = "GMT") @ \mysection[1. I know that duplicate times are not allowed but my data has them. What do I do?]{1. I know that duplicate times are not allowed but my data has them. What do I do?} \pkg{zoo} objects should not normally contain duplicate times. If you try to create such an object using \pkg{zoo} or \code{read.zoo} then warnings will be issued but the objects will be created. The user then has the opportunity to fix them up -- typically by using \code{aggregate.zoo} or \code{duplicated}. Merging is not well defined for duplicate series with duplicate times and rather than give an undesired or unexpected result, \code{merge.zoo} issues an error message if it encounters such illegal objects. Since \code{merge.zoo} is the workhorse behind many \pkg{zoo} functions, a significant portion of \pkg{zoo} will not accept duplicates among the times. Typically duplicates are eliminated by (1)~averaging over them, (2)~taking the last among each run of duplicates or (3)~interpolating the duplicates and deleting ones on the end that cannot be interpolated. These three approaches are shown here using the \code{aggregate.zoo} function. Another way to do this is to use the \code{aggregate} argument of \code{read.zoo} which will aggregate the zoo object read in by \code{read.zoo} all in one step. Note that in the example code below that \code{identity} is the identity function (i.e. it just returns its argument). It is an \proglang{R} core function: A \code{"zoo"} series with duplicated indexes <>= z <- suppressWarnings(zoo(1:8, c(1, 2, 2, 2, 3, 4, 5, 5))) z @ Fix it up by averaging duplicates: <>= aggregate(z, identity, mean) @ Or, fix it up by taking last in each set of duplicates: <>= aggregate(z, identity, tail, 1) @ Fix it up via interpolation of duplicate times <>= time(z) <- na.approx(ifelse(duplicated(time(z)), NA, time(z)), na.rm = FALSE) @ If there is a run of equal times at end they wind up as \code{NA}s and we cannot have \code{NA} times. <>= z[!is.na(time(z))] @ %% An alternative to aggregating the data is to make the times unique %% by changing them slightly. The facilities here are limited to %% time classes for %% which addition by a number makes sense. See the \code{make.unique.approx} %% and \code{make.unique.incr} functions which use interpolation or %% incrementing by a fixed number. Interpolation has the further restriction %% that the interpolated result must make sense. For example, it makes sense to %% interpolate \code{"POSIXct"} variables but not \code{"Date"} variables since %% the interpolation may fall between dates. %% Also see the \code{make.unique} %% argument to \code{read.zoo} which allows one to read in the data %% and make it unique all in one operation. The \code{read.zoo} command has an \code{aggregate} argument that supports arbitrary summarization. For example, in the following we take the last value among any duplicate times and sum the volumes among all duplicate times. We do this by reading the data twice, once for each aggregate function. In this example, the first three columns are junk that we wish to suppress which is why we specified \code{colClasses}; however, in most cases that argument would not be necessary. <>= Lines <- "1|BHARTIARTL|EQ|18:15:05|600|1 2|BHARTIARTL|EQ|18:15:05|600|99 3|GLENMARK|EQ|18:15:05|238.1|5 4|HINDALCO|EQ|18:15:05|43.75|100 5|BHARTIARTL|EQ|18:15:05|600|1 6|BHEL|EQ|18:15:05|1100|11 7|HINDALCO|EQ|18:15:06|43.2|1 8|CHAMBLFERT|EQ|18:15:06|46|10 9|CHAMBLFERT|EQ|18:15:06|46|90 10|BAJAUTOFIN|EQ|18:15:06|80|100" library("zoo") library("chron") tail1 <- function(x) tail(x, 1) cls <- c("NULL", "NULL", "NULL", "character", "numeric", "numeric") nms <- c("", "", "", "time", "value", "volume") z <- read.zoo(textConnection(Lines), aggregate = tail1, FUN = times, sep = "|", colClasses = cls, col.names = nms) z2 <- read.zoo(textConnection(Lines), aggregate = sum, FUN = times, sep = "|", colClasses = cls, col.names = nms) z$volume <- z2$volume z @ If the reason for the duplicate times is that the data is stored in long format then use \code{read.zoo} (particlarly the \code{split} argument) to convert it to wide format. Wide format is typically a time series whereas long format is not so wide format is the suitable one for zoo. <>= Lines <- "Date Stock Price 2000-01-01 IBM 10 2000-01-02 IBM 11 2000-01-01 ORCL 12 2000-01-02 ORCL 13" stocks <- read.zoo(textConnection(Lines), header = TRUE, split = "Stock") stocks @ \mysection[2. When I try to specify a log axis to plot.zoo a warning is issued. What is wrong?]{2. When I try to specify a log axis to \code{plot.zoo} a warning is issued. What is wrong?} Arguments that are part of \code{...} are passed to the \code{panel} function and the default \code{panel} function, \code{lines}, does not accept \code{log}. Either ignore the warning, use \code{suppressWarnings} (see \code{?suppressWarnings}) or create your own panel function which excludes the \code{log}: <>= z <- zoo(1:100) plot(z, log = "y", panel = function(..., log) lines(...)) @ \mysection[3. How do I create right and a left vertical axes in plot.zoo?]{3. How do I create right and a left vertical axes in \code{plot.zoo}?} The following shows an example of creating a plot containing a single panel and both left and right axes. <>= set.seed(1) z.Date <- as.Date(paste(2003, 02, c(1, 3, 7, 9, 14), sep = "-")) z <- zoo(cbind(left = rnorm(5), right = rnorm(5, sd = 0.2)), z.Date) plot(z[,1], xlab = "Time", ylab = "") opar <- par(usr = c(par("usr")[1:2], range(z[,2]))) lines(z[,2], lty = 2) axis(side = 4) legend("bottomright", lty = 1:2, legend = colnames(z), bty="n") par(opar) @ \begin{figure}[htbp] \begin{center} <>= <> @ \caption{\label{fig:plot-axes} Left and right \code{plot.zoo} axes.} \end{center} \end{figure} \mysection[4. I have data frame with both numeric and factor columns. How do I convert that to a "zoo" object?]{4. I have data frame with both numeric and factor columns. How do I convert that to a \code{"zoo"} object?} A \code{"zoo"} object may be (1)~a numeric vector, (2)~a numeric matrix or (3)~a factor but may not contain both a numeric vector and factor. The underlying reason for this constraint is that \code{"zoo"} was intended to generalize \proglang{R}'s \code{"ts"} class, which is also based on matrices, to irregularly spaced series with an arbitrary index class. The main reason to stick to matrices is that operations on matrices in \proglang{R} are much faster than on data frames. If you have a data frame with both numeric and factor variables that you want to convert to \code{"zoo"}, you can do one of the following. Use two \code{"zoo"} variables instead: <>= DF <- data.frame(time = 1:4, x = 1:4, f = factor(letters[c(1, 1, 2, 2)])) zx <- zoo(DF$x, DF$time) zf <- zoo(DF$f, DF$time) @ These could also be held in a \code{"data.frame"} again: <>= DF2 <- data.frame(x = zx, f = zf) @ Or convert the factor to numeric and create a single \code{"zoo"} series: <>= z <- zoo(data.matrix(DF[-1]), DF$time) @ \mysection[5. Why does lag give slightly different results on a "zoo" and a "zooreg" series which are otherwise the same?]{5. Why does lag give slightly different results on a \code{"zoo"} and a \code{"zooreg"} series which are otherwise the same?} To be definite let us consider the following examples, noting how both \code{lag} and \code{diff} give a different answer with the same input except its class is \code{"zoo"} in one case and \code{"zooreg"} in another: <>= z <- zoo(11:15, as.Date("2008-01-01") + c(-4, 1, 2, 3, 6)) zr <- as.zooreg(z) lag(z) lag(zr) diff(log(z)) diff(log(zr)) @ \code{lag.zoo} and \code{lag.zooreg} work differently. For \code{"zoo"} objects the lagged version is obtained by moving values to the adjacent time point that exists in the series but for \code{"zooreg"} objects the time is lagged by \code{deltat}, the time between adjacent regular times. A key implication is that \code{"zooreg"} can lag a point to a time point that did not previously exist in the series and, in particular, can lag a series outside of the original time range whereas that is not possible in a \code{"zoo"} series. Note that \code{lag.zoo} has an \code{na.pad=} argument which in some cases may be what is being sought here. The difference between \code{diff.zoo} and \code{diff.zooreg} stems from the fact that \code{diff(x)} is defined in terms of \code{lag} like this: \code{x-lag(x,-1)}. \mysection[6. How do I subtract the mean of each month from a "zoo" series?]{6. How do I subtract the mean of each month from a \code{"zoo"} series?} Suppose we have a daily series. To subtract the mean of Jan 2007 from each day in that month, subtract the mean of Feb 2007 from each day in that month, etc. try this: <>= set.seed(123) z <- zoo(rnorm(100), as.Date("2007-01-01") + seq(0, by = 10, length = 100)) z.demean1 <- z - ave(z, as.yearmon(time(z))) @ This first generates some artificial data and then employs \code{ave} to compute monthly means. To subtract the mean of all Januaries from each January, etc. try this: <>= z.demean2 <- z - ave(z, format(time(z), "%m")) @ \mysection[7. How do I create a monthly series but still keep track of the dates?]{7. How do I create a monthly series but still keep track of the dates?} Create a \proglang{S}3 subclass of \code{"yearmon"} called \code{"yearmon2"} that stores the dates as names on the time vector. It will be sufficient to create an \code{as.yearmon2} generic together with an \code{as.yearmon2.Date} methods as well as the inverse: \code{as.Date.yearmon2}. <>= as.yearmon2 <- function(x, ...) UseMethod("as.yearmon2") as.yearmon2.Date <- function(x, ...) { y <- as.yearmon(with(as.POSIXlt(x, tz = "GMT"), 1900 + year + mon/12)) names(y) <- x structure(y, class = c("yearmon2", class(y))) } @ \code{as.Date.yearmon2} is inverse of \code{as.yearmon2.Date} <>= as.Date.yearmon2 <- function(x, frac = 0, ...) { if (!is.null(names(x))) return(as.Date(names(x))) x <- unclass(x) year <- floor(x + .001) month <- floor(12 * (x - year) + 1 + .5 + .001) dd.start <- as.Date(paste(year, month, 1, sep = "-")) dd.end <- dd.start + 32 - as.numeric(format(dd.start + 32, "%d")) as.Date((1-frac) * as.numeric(dd.start) + frac * as.numeric(dd.end), origin = "1970-01-01") } @ This new class will act the same as \code{"yearmon"} stores and allows recovery of the dates using \code{as.Date} and \code{aggregate.zoo}. <>= dd <- seq(as.Date("2000-01-01"), length = 5, by = 32) z <- zoo(1:5, as.yearmon2(dd)) z aggregate(z, as.Date, identity) @ \mysection[8. How are axes added to a plot created using plot.zoo?]{8. How are axes added to a plot created using \code{plot.zoo}?} On single panel plots \code{axis} or \code{Axis} can be used just as with any classic graphics plot in \proglang{R}. The following example adds custom axis for single panel plot. It labels months but uses the larger year for January. Months, quarters and years should have successively larger ticks. <>= z <- zoo(0:500, as.Date(0:500)) plot(z, xaxt = "n") tt <- time(z) m <- unique(as.Date(as.yearmon(tt))) jan <- format(m, "%m") == "01" mlab <- substr(months(m[!jan]), 1, 1) axis(side = 1, at = m[!jan], labels = mlab, tcl = -0.3, cex.axis = 0.7) axis(side = 1, at = m[jan], labels = format(m[jan], "%y"), tcl = -0.7) axis(side = 1, at = unique(as.Date(as.yearqtr(tt))), labels = FALSE) abline(v = m, col = grey(0.8), lty = 2) @ A multivariate series can either be generated as (1)~multiple single panel plots: <>= z3 <- cbind(z1 = z, z2 = 2*z, z3 = 3*z) opar <- par(mfrow = c(2, 2)) tt <- time(z) m <- unique(as.Date(as.yearmon(tt))) jan <- format(m, "%m") == "01" mlab <- substr(months(m[!jan]), 1, 1) for(i in 1:ncol(z3)) { plot(z3[,i], xaxt = "n", ylab = colnames(z3)[i], ylim = range(z3)) axis(side = 1, at = m[!jan], labels = mlab, tcl = -0.3, cex.axis = 0.7) axis(side = 1, at = m[jan], labels = format(m[jan], "%y"), tcl = -0.7) axis(side = 1, at = unique(as.Date(as.yearqtr(tt))), labels = FALSE) } par(opar) @ or (2)~as a multipanel plot. In this case any custom axis must be placed in a panel function. <>= plot(z3, screen = 1:3, xaxt = "n", nc = 2, ylim = range(z3), panel = function(...) { lines(...) panel.number <- parent.frame()$panel.number nser <- parent.frame()$nser # place axis on bottom panel of each column only if (panel.number %% 2 == 0 || panel.number == nser) { tt <- list(...)[[1]] m <- unique(as.Date(as.yearmon(tt))) jan <- format(m, "%m") == "01" mlab <- substr(months(m[!jan]), 1, 1) axis(side = 1, at = m[!jan], labels = mlab, tcl = -0.3, cex.axis = 0.7) axis(side = 1, at = m[jan], labels = format(m[jan], "%y"), tcl = -0.7) axis(side = 1, at = unique(as.Date(as.yearqtr(tt))), labels = FALSE) } }) @ \mysection[9. Why is nothing plotted except axes when I plot an object with many NAs?]{9. Why is nothing plotted except axes when I plot an object with many \code{NA}s?} Isolated points surrounded by \code{NA} values do not form lines: <>= z <- zoo(c(1, NA, 2, NA, 3)) plot(z) @ So try one of the following: Plot points rather than lines. <>= plot(z, type = "p") @ Omit \code{NA}s and plot that. <>= plot(na.omit(z)) @ Fill in the \code{NA}s with interpolated values. <>= plot(na.approx(z)) @ Plot points with lines superimposed. <>= plot(z, type = "p") lines(na.omit(z)) @ Note that this is not specific to \pkg{zoo.} If we plot in \proglang{R} without \pkg{zoo} we get the same behavior. \mysection[10. Does zoo work with Rmetrics?]{10. Does \pkg{zoo} work with \pkg{Rmetrics}?} Yes. \code{timeDate} class objects from the \pkg{timeDate} package can be used directly as the index of a \code{zoo} series and \code{as.timeSeries.zoo} and \code{as.zoo.timeSeries} can convert back and forth between objects of class \code{zoo} and class \code{timeSeries} from the \pkg{timeSeries} package. <>= library("timeDate") dts <- c("1989-09-28", "2001-01-15", "2004-08-30", "1990-02-09") tms <- c( "23:12:55", "10:34:02", "08:30:00", "11:18:23") td <- timeDate(paste(dts, tms), format = "%Y-%m-%d %H:%M:%S") library("zoo") z <- zoo(1:4, td) zz <- merge(z, lag(z)) plot(zz) library("timeSeries") zz as.timeSeries(zz) as.zoo(as.timeSeries(zz)) @ <>= detach("package:timeSeries") detach("package:timeDate") @ \mysection[11. What other packages use zoo?]{11. What other packages use \pkg{zoo}?} A DEIS dependency means that a package lists \pkg{zoo} in the Depends, Enhances, Imports or Suggests clause of their DESCRIPTION file. As of September 27, 2011 there are 65 packages on CRAN with DEIS dependencies on zoo and 207 packages which either have direct DEIS dependencies or a DEIS dependency on a package which in turn has a DEIS dependency on zoo. This suggests that packages that have a DEIS dependency on zoo are themselves popular. If one recursively calculates DEIS dependencies to all depths then 2127 packages on CRAN have direct or indirect DEIS dependencies on zoo. That is over half of CRAN. Below are 74 packages which include those with direct DEIS dependencies as well as packages that are often used with zoo: Some packages depend on zoo indirectly listing such a relationship to a package which in turn has such a dependency on zoo. There are 207 packages which There are 74 other CRAN packages that are or can be used with \pkg{zoo} (and possibly more in other repositories): \begin{center} \begin{tabular}{|p{3.6cm}|p{11cm}|} \hline \multicolumn{2}{|l|}{\emph{Depends}} \\ \hline \pkg{AER} & Applied Econometrics with R \\ \hline \pkg{BootPR} & Bootstrap Prediction Intervals and Bias-Corrected Forecasting \\ \hline \pkg{DMwR} & Functions and data for "Data Mining with R" \\ \hline \pkg{FinTS} & Companion to Tsay (2005) Analysis of Financial Time Series \\ \hline \pkg{MFDF} & Modeling Functional Data in Finance \\ \hline \pkg{Modalclust} & Hierarchical Modal Clustering \\ \hline \pkg{PerformanceAnalytics} & Econometric tools for performance and risk analysis \\ \hline \pkg{RBloomberg} & R/Bloomberg \\ \hline \pkg{RghcnV3} & Global Historical Climate Network Version 3 \\ \hline \pkg{StreamMetabolism} & Stream Metabolism-A package for calculating single station metabolism from diurnal Oxygen curves \\ \hline \pkg{TSfame} & Time Series Database Interface extensions for fame \\ \hline \pkg{TShistQuote} & Time Series Database Interface extensions for get.hist.quote \\ \hline \pkg{TSxls} & Time Series Database Interface extension to connect to spreadsheets \\ \hline \pkg{VhayuR} & Vhayu R Interface \\ \hline \pkg{delftfews} & delftfews R extensions \\ \hline \pkg{dyn} & Time Series Regression \\ \hline \pkg{dynlm} & Dynamic Linear Regression \\ \hline \pkg{fda} & Functional Data Analysis \\ \hline \pkg{forecast} & Forecasting functions for time series \\ \hline \pkg{fractalrock} & Generate fractal time series with non-normal returns distribution \\ \hline \pkg{fxregime} & Exchange Rate Regime Analysis \\ \hline \pkg{glogis} & Fitting and Testing Generalized Logistic Distributions \\ \hline \pkg{hydroTSM} & Time series management, analysis and interpolation for hydrological modelling \\ \hline \pkg{lmtest} & Testing Linear Regression Models \\ \hline \pkg{meboot} & Maximum Entropy Bootstrap for Time Series \\ \hline \pkg{mlogit} & multinomial logit model \\ \hline \pkg{party} & A Laboratory for Recursive Partytioning \\ \hline \pkg{quantmod} & Quantitative Financial Modelling Framework \\ \hline \pkg{rdatamarket} & Data access API for DataMarket.com \\ \hline \pkg{sandwich} & Robust Covariance Matrix Estimators \\ \hline \pkg{sde} & Simulation and Inference for Stochastic Differential Equations \\ \hline \pkg{solaR} & Solar Photovoltaic Systems \\ \hline \pkg{spacetime} & classes and methods for spatio-temporal data \\ \hline \pkg{strucchange} & Testing, Monitoring, and Dating Structural Changes \\ \hline \pkg{tawny} & Provides various portfolio optimization strategies including random matrix theory and shrinkage estimators \\ \hline \pkg{termstrc} & Zero-coupon Yield Curve Estimation \\ \hline \pkg{tgram} & Functions to compute and plot tracheidograms \\ \hline \pkg{tripEstimation} & Metropolis sampler and supporting functions for estimating animal movement from archival tags and satellite fixes \\ \hline \pkg{tseries} & Time series analysis and computational finance \\ \hline \pkg{wq} & Exploring water quality monitoring data \\ \hline \pkg{xts} & eXtensible Time Series \\ \hline \end{tabular} \end{center} \begin{center} \begin{tabular}{|p{3.6cm}|p{11cm}|} \hline \multicolumn{2}{|l|}{\emph{Enhances}} \\ \hline \pkg{chron} & Chronological objects which can handle dates and times \\ \hline \pkg{hydroTSM} & Time series management, analysis and interpolation for hydrological modelling \\ \hline \pkg{lubridate} & Make dealing with dates a little easier \\ \hline \pkg{tis} & Time Indexes and Time Indexed Series \\ \hline \end{tabular} \begin{tabular}{|p{3.6cm}|p{11cm}|} \hline \multicolumn{2}{|l|}{\emph{Imports}} \\ \hline \pkg{fxregime} & Exchange Rate Regime Analysis \\ \hline \pkg{glogis} & Fitting and Testing Generalized Logistic Distributions \\ \hline \pkg{hydroGOF} & Goodness-of-fit functions for comparison of simulated and observed hydrological time series \\ \hline \pkg{openair} & Tools for the analysis of air pollution data \\ \hline \pkg{rasterVis} & Visualization methods for the raster package \\ \hline \end{tabular} \end{center} \begin{center} \begin{tabular}{|p{3.6cm}|p{11cm}|} \hline \multicolumn{2}{|l|}{\emph{Suggests}} \\ \hline \pkg{MeDiChI} & MeDiChI ChIP-chip deconvolution library \\ \hline \pkg{RQuantLib} & R interface to the QuantLib library \\ \hline \pkg{TSAgg} & Time series Aggregation \\ \hline \pkg{TSMySQL} & Time Series Database Interface extensions for MySQL \\ \hline \pkg{TSPostgreSQL} & Time Series Database Interface extensions for PostgreSQL \\ \hline \pkg{TSSQLite} & Time Series Database Interface extentions for SQLite \\ \hline \pkg{TSdbi} & Time Series Database Interface \\ \hline \pkg{TSodbc} & Time Series Database Interface extensions for ODBC \\ \hline \pkg{TSzip} & Time Series Database Interface extension to connect to zip files \\ \hline \pkg{UsingR} & Data sets for the text "Using R for Introductory Statistics" \\ \hline \pkg{Zelig} & Everyone's Statistical Software \\ \hline \pkg{gsubfn} & Utilities for strings and function arguments \\ \hline \pkg{latticeExtra} & Extra Graphical Utilities Based on Lattice \\ \hline \pkg{mondate} & Keep track of dates in terms of months \\ \hline \pkg{playwith} & A GUI for interactive plots using GTK+ \\ \hline \pkg{pscl} & Political Science Computational Laboratory, Stanford University \\ \hline \pkg{quantreg} & Quantile Regression \\ \hline \pkg{tframePlus} & Time Frame coding kernel extensions \\ \hline \end{tabular} \end{center} \begin{center} \begin{tabular}{|p{3.6cm}|p{11cm}|} \hline \multicolumn{2}{|l|}{\emph{Uses or Used with}} \\ \hline \pkg{timeDate} & \pkg{Rmetrics} date and time functions: \code{timeDate} usable with \code{zoo} \\ \hline \pkg{grid} & Graphics infrastructure: use with \code{xyplot.zoo} \\ \hline \pkg{its} & Irregular time series: \code{as.its.zoo}, \code{as.zoo.its} \\ \hline \pkg{lattice} & \pkg{grid}-based graphics: use with \code{xyplot.zoo} \\ \hline \pkg{timeSeries} & \pkg{Rmetrics} time series functions: \code{as.timeSeries.zoo}, \code{as.zoo.timeSeries} \\ \hline \pkg{YaleToolkit} & Data exploration tools from Yale University: accepts \code{"zoo"} input \\ \hline \end{tabular} \end{center} \mysection[12. Why does ifelse not work as I expect?]{12. Why does \code{ifelse} not work as I expect?} The ordinary \proglang{R} \code{ifelse} function only works with zoo objects if all three arguments are zoo objects with the same time index. \pkg{zoo} provides an \code{ifelse.zoo} function that should be used instead. The \code{.zoo} part must be written out since \code{ifelse} is not generic. <>= z <- zoo(c(1, 5, 10, 15)) # wrong !!! ifelse(diff(z) > 4, -z, z) # ok ifelse.zoo(diff(z) > 4, -z, z) # or if we merge first we can use ordinary ifelse xm <- merge(z, dif = diff(z)) with(xm, ifelse(dif > 4, -z, z)) # or in this case we could also use orindary ifelse if we # use fill = NA to ensure all three have same index ifelse(diff(z, fill = NA) > 4, -z, z) @ \mysection[13. In a series which is regular except for a few missing times or for which we wish to align to a grid how is it filled in or aligned?]{13. In a series which is regular except for a few missing times or for which we wish to align to a grid how is it filled or aligned?} <>= # April is missing zym <- zoo(1:5, as.yearmon("2000-01-01") + c(0, 1, 2, 4, 5)/12) g <- seq(start(zym), end(zym), by = 1/12) na.locf(zym, xout = g) @ A variation of this is where the grid is of a different date/time class than the original series. In that case use the \code{x} argument. In the example that follows the series \code{z} is of \code{"Date"} class whereas the grid is of \code{"yearmon"} class: <>= z <- zoo(1:3, as.Date(c("2000-01-15", "2000-03-3", "2000-04-29"))) g <- seq(as.yearmon(start(z)), as.yearmon(end(z)), by = 1/12) na.locf(z, x = as.yearmon, xout = g) @ Here is a \code{chron} example where we wish to create a 10 minute grid: <>= Lines <- "Time,Value 2009-10-09 5:00:00,210 2009-10-09 5:05:00,207 2009-10-09 5:17:00,250 2009-10-09 5:30:00,193 2009-10-09 5:41:00,205 2009-10-09 6:00:00,185" library("chron") z <- read.zoo(textConnection(Lines), FUN = as.chron, sep = ",", header = TRUE) g <- seq(start(z), end(z), by = times("00:10:00")) na.locf(z, xout = g) @ \mysection[14. What is the difference between as.Date in zoo and as.Date in the core of R?]{What is the difference between \code{as.Date} in zoo and \code{as.Date} in the core of R?} zoo has extended the \code{origin} argument of \code{as.Date.numeric} so that it has a default of \code{origin="1970-01-01"} (whereas in the core of R it has no default and must always be specified). Note that this is a strictly upwardly compatible extensions to R and any usage of \code{as.Date} in R will also work in zoo. This makes it more convenient to use as.Date as a function input. For example, one can shorten this: <>= z <- zoo(1:2, c("2000-01-01", "2000-01-02")) aggregate(z, function(x) as.Date(x, origin = "1970-01-01")) @ to just this: <>= aggregate(z, as.Date) @ As another example, one can shorten <>= Lines <- "2000-01-01 12:00:00,12 2000-01-02 12:00:00,13" read.zoo(text = Lines, sep = ",", FUN = function(x) as.Date(x, origin = "1970-01-01")) @ to this: <>= read.zoo(text = Lines, sep = ",", FUN = as.Date) @ Note to package developers of packages that use zoo: Other packages that work with zoo and define \code{as.Date} methods should either import \pkg{zoo} or else should fully export their \code{as.Date} methods in their \code{NAMESPACE} file, e.g. \code{export(as.Date.X)}, in order that those methods be registered with \pkg{zoo}'s \code{as.Date} generic and not just the \code{as.Date} generic in \pkg{base}. \mysection[15. How can I speed up zoo?]{15. How can I speed up zoo?} The main area where you might notice slowness is if you do indexing of zoo objects in an inner loop. In that case extract the data and time components prior to the loop. Since most calculations in R use the whole object approach there are relatively few instances of this. For example, the following shows two ways of performing a rolling sum using only times nearer than 3 before the current time. The second one eliminates the zoo indexing to get a speedup: <>= n <- 50 z <- zoo(1:n, c(1:3, seq(4, by = 2, length = n-3))) system.time({ zz <- sapply(seq_along(z), function(i) sum(z[time(z) <= time(z)[i] & time(z) > time(z)[i] - 3])) z1 <- zoo(zz, time(z)) }) system.time({ zc <- coredata(z) tt <- time(z) zr <- sapply(seq_along(zc), function(i) sum(zc[tt <= tt[i] & tt > tt[i] - 3])) z2 <- zoo(zr, tt) }) identical(z1, z2) @ \end{document} zoo/vignettes/zoo-design.Rnw0000644000175400001440000001034711747047642016053 0ustar zeileisusers\documentclass[article,nojss]{jss} %% need no \usepackage{Sweave} \title{\pkg{zoo} Design} \Plaintitle{zoo Design} \author{\pkg{zoo} Development Team} \Plainauthor{zoo Development Team} \Address{ \pkg{zoo} Development Team\\ \proglang{R}-Forge: \url{http://R-Forge.R-project.org/projects/zoo/}\\ Comprehensive \proglang{R} Archive Network: \url{http://CRAN.R-project.org/package=zoo} } \Keywords{irregular time series, ordered observations, time index} \Abstract{ This is a set of design principles that -- albeit not having been explicitly set out initially -- have guided the development of the \proglang{R} \pkg{zoo} package. } \begin{document} \SweaveOpts{engine=R,eps=FALSE} %\VignetteIndexEntry{zoo Design} %\VignetteDepends{zoo} %\VignetteKeywords{irregular time series, ordered observations, time index} %\VignettePackage{zoo} <>= library("zoo") Sys.setenv(TZ = "GMT") @ \emph{\pkg{zoo} works with any ordered index class} having the prescribed methods, see \code{?zoo} and \cite{zoo:Zeileis+Grothendieck:2005}. Specific index classes are not hard-coded in functions (with a few exceptions necessitated by external interfaces such as reading and interfacing with `\code{ts}') but rather all index operations are only done via the allowed methods. \emph{\pkg{zoo} is invisible}. As far as possible new names (e.g., for functions or methods and their arguments) are not introduced. New functionality is added as methods to generics from base \proglang{R} allowing reuse of those names. When names are added, thought is put into the name since \pkg{zoo} is so miserly about adding them. For example, the \code{read.zoo} name is obviously derived from \code{read.table} and the names \code{na.locf} or \code{na.approx} are in analogy to other \code{na.*} functions frome base \proglang{R}. \emph{\pkg{zoo} is consistent with base \proglang{R}}. The idea is to make the usage of \pkg{zoo} completely natural to someone who already has experience with \proglang{R} (in particular with the `\code{ts}' class). Certainly, \pkg{zoo} contains extensions to base \proglang{R}, but they should be as consistent as possible and have a natural `look and feel'. \emph{\pkg{zoo} is infrastructure}. \pkg{zoo} tries to do basic things well, e.g., data reading, handling, aggregation, transformation, etc. However, it does not provide time series modeling functionality -- \pkg{zoo} rather encourages add-on packages. A list of current packages employing \pkg{zoo} can be found on the Comprehensive \proglang{R} Archive Network (CRAN) and in the \pkg{zoo} FAQ, see \code{vignette("zoo-faq", package = "zoo")}. \emph{\pkg{zoo} interfaces to all other time series packages} on CRAN (or at least all of the more popular ones and some of the relatively unknown ones as well). Thus, time series information can be passed back and forth relatively easily between `\code{zoo}' and other time series classes and hence combinations of various functionalities are facilitated. \emph{\pkg{zoo} includes extensive documentation}. In addition to the standard \code{help()} pages, \pkg{zoo} provides a set of vignettes, see \code{vignette(package = "zoo")} for a list. Furthermore, the \pkg{zoo} Development Team members also post frequently on the mailing lists (especially ``\proglang{R}-help'', ``\proglang{R}-devel'', and ``\proglang{R}-SIG-Finance'') whose archives hence contain many useful code snippets etc. \emph{\pkg{zoo} has no bug list since all bugs are fixed (almost) immediately}. Over the last years, \pkg{zoo} has grown into a mature package. Nevertheless, there are always still bugs (or border cases that are not handled well). When reported to the development team by e-mail, these typically get fixed immediately in the Subversion (SVN) repository on \proglang{R}-Forge. (As of this writing, there are a couple of entries in the \pkg{zoo} \proglang{R}-Forge bug list, however typically this is not the situation.) \emph{\pkg{zoo} includes formal regression testing}. We have started developing formal regression tests employing \proglang{R}'s own system (in \code{zoo/tests/}) as well as the \pkg{RUnit} package \citep{zoo:RUnit}. \bibliography{zoo} \end{document} zoo/vignettes/sunw.rda0000644000175400001440000004046611747047642014776 0ustar zeileisusersRDX2 X  sunw@\(@ =p @ffffff@(\)@(\)@Q@ =p@@\(\@Q@(\)@@\(\@Q@\(@zG@QR@ffffff@Gz@\(@=p =@Gz@GzH@\(@333333@Q@\(\@p =q@ =p @QR@Gz@Q@\(\@ =p@Q@@zG@\(@ =p@Q@=p =@Q@zG@Gz@@333333@333333@(\)@Q@QR@ =p@zG@\(@zG{@ =p @p =q@ =p @(\)@\(@ =p@Q@Q@@=p =@Q@(\)@Q@Q@ =p @Q@ =p @QR@\(@ =p@GzH@zG@\(@GzH@\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rc'Ra{c8Nz'ugױ{mĉ ,;ri}$#뻊}1{>Hc>۟ *\钼e] =R-%߷>uӳx8$DNb~{&>ʞbǧw'>MoxIDN&q8x GK?պ;ZݳD}ԥ;ykԓ ################################################### > ### chunk number 1: preliminaries > ################################################### > library("zoo") Attaching package: 'zoo' The following object is masked from 'package:base': as.Date, as.Date.numeric > library("tseries") > library("strucchange") Loading required package: sandwich > library("timeDate") > online <- FALSE ## if set to FALSE the local copy of MSFT.rda > ## is used instead of get.hist.quote() > options(prompt = "R> ") R> Sys.setenv(TZ = "GMT") R> R> R> ################################################### R> ### chunk number 2: zoo-prelim R> ################################################### R> library("zoo") R> set.seed(1071) R> R> R> ################################################### R> ### chunk number 3: zoo-vectors1 R> ################################################### R> z1.index <- ISOdatetime(2004, rep(1:2,5), sample(28,10), 0, 0, 0) R> z1.data <- rnorm(10) R> z1 <- zoo(z1.data, z1.index) R> R> R> ################################################### R> ### chunk number 4: zoo-vectors2 R> ################################################### R> z2.index <- as.POSIXct(paste(2004, rep(1:2, 5), sample(1:28, 10), sep = "-")) R> z2.data <- sin(2*1:10/pi) R> z2 <- zoo(z2.data, z2.index) R> R> R> ################################################### R> ### chunk number 5: zoo-matrix R> ################################################### R> Z.index <- as.Date(sample(12450:12500, 10)) R> Z.data <- matrix(rnorm(30), ncol = 3) R> colnames(Z.data) <- c("Aa", "Bb", "Cc") R> Z <- zoo(Z.data, Z.index) R> R> R> ################################################### R> ### chunk number 6: print1 R> ################################################### R> z1 2004-01-05 2004-01-14 2004-01-19 2004-01-25 2004-01-27 2004-02-07 0.74675994 0.02107873 -0.29823529 0.68625772 1.94078850 1.27384445 2004-02-12 2004-02-16 2004-02-20 2004-02-24 0.22170438 -2.07607585 -1.78439244 -0.19533304 R> z1[3:7] 2004-01-19 2004-01-25 2004-01-27 2004-02-07 2004-02-12 -0.2982353 0.6862577 1.9407885 1.2738445 0.2217044 R> R> R> ################################################### R> ### chunk number 7: print2 R> ################################################### R> Z Aa Bb Cc 2004-02-02 1.2554339 0.6815732 -0.63292049 2004-02-08 -1.4945833 1.3234122 -1.49442269 2004-02-09 -1.8746225 -0.8732929 0.62733971 2004-02-21 -0.1453861 0.4523490 -0.14597401 2004-02-22 0.2254242 0.5383894 0.23136133 2004-02-29 1.2069552 0.3181422 -0.01129202 2004-03-05 -1.2086102 1.4237978 -0.81614483 2004-03-10 -0.1103956 1.3477425 0.95522468 2004-03-14 0.8420238 -2.7384202 0.23150695 2004-03-20 -0.1901910 0.1230887 -1.51862157 R> Z[1:3, 2:3] Bb Cc 2004-02-02 0.6815732 -0.6329205 2004-02-08 1.3234122 -1.4944227 2004-02-09 -0.8732929 0.6273397 R> R> R> ################################################### R> ### chunk number 8: subset R> ################################################### R> z1[ISOdatetime(2004, 1, c(14, 25), 0, 0, 0)] 2004-01-14 2004-01-25 0.02107873 0.68625772 R> R> R> ################################################### R> ### chunk number 9: summary R> ################################################### R> summary(z1) Index z1 Min. :2004-01-05 00:00:00 Min. :-2.07608 1st Qu.:2004-01-20 12:00:00 1st Qu.:-0.27251 Median :2004-02-01 12:00:00 Median : 0.12139 Mean :2004-02-01 09:36:00 Mean : 0.05364 3rd Qu.:2004-02-15 00:00:00 3rd Qu.: 0.73163 Max. :2004-02-24 00:00:00 Max. : 1.94079 R> summary(Z) Index Aa Bb Cc Min. :2004-02-02 Min. :-1.8746 Min. :-2.7384 Min. :-1.51862 1st Qu.:2004-02-12 1st Qu.:-0.9540 1st Qu.: 0.1719 1st Qu.:-0.77034 Median :2004-02-25 Median :-0.1279 Median : 0.4954 Median :-0.07863 Mean :2004-02-25 Mean :-0.1494 Mean : 0.2597 Mean :-0.25739 3rd Qu.:2004-03-08 3rd Qu.: 0.6879 3rd Qu.: 1.1630 3rd Qu.: 0.23147 Max. :2004-03-20 Max. : 1.2554 Max. : 1.4238 Max. : 0.95522 R> R> R> ################################################### R> ### chunk number 10: zooreg1 R> ################################################### R> zr1 <- zooreg(sin(1:9), start = 2000, frequency = 4) R> zr2 <- zoo(sin(1:9), seq(2000, 2002, by = 1/4), 4) R> zr1 2000(1) 2000(2) 2000(3) 2000(4) 2001(1) 2001(2) 2001(3) 0.8414710 0.9092974 0.1411200 -0.7568025 -0.9589243 -0.2794155 0.6569866 2001(4) 2002(1) 0.9893582 0.4121185 R> zr2 2000(1) 2000(2) 2000(3) 2000(4) 2001(1) 2001(2) 2001(3) 0.8414710 0.9092974 0.1411200 -0.7568025 -0.9589243 -0.2794155 0.6569866 2001(4) 2002(1) 0.9893582 0.4121185 R> R> R> ################################################### R> ### chunk number 11: zooreg2 R> ################################################### R> zr1 <- zr1[-c(3, 5)] R> zr1 2000(1) 2000(2) 2000(4) 2001(2) 2001(3) 2001(4) 2002(1) 0.8414710 0.9092974 -0.7568025 -0.2794155 0.6569866 0.9893582 0.4121185 R> class(zr1) [1] "zooreg" "zoo" R> frequency(zr1) [1] 4 R> R> R> ################################################### R> ### chunk number 12: zooreg1b R> ################################################### R> zooreg(1:5, start = as.Date("2005-01-01")) 2005-01-01 2005-01-02 2005-01-03 2005-01-04 2005-01-05 1 2 3 4 5 R> R> R> ################################################### R> ### chunk number 13: zooreg3 R> ################################################### R> is.regular(zr1) [1] TRUE R> is.regular(zr1, strict = TRUE) [1] FALSE R> R> R> ################################################### R> ### chunk number 14: zooreg4 R> ################################################### R> zr1 <- as.zoo(zr1) R> zr1 2000 2000.25 2000.75 2001.25 2001.5 2001.75 2002 0.8414710 0.9092974 -0.7568025 -0.2794155 0.6569866 0.9893582 0.4121185 R> class(zr1) [1] "zoo" R> is.regular(zr1) [1] TRUE R> frequency(zr1) [1] 4 R> R> R> ################################################### R> ### chunk number 15: zooreg5 R> ################################################### R> as.ts(zr1) Qtr1 Qtr2 Qtr3 Qtr4 2000 0.8414710 0.9092974 NA -0.7568025 2001 NA -0.2794155 0.6569866 0.9893582 2002 0.4121185 R> identical(zr2, as.zoo(as.ts(zr2))) [1] TRUE R> R> R> ################################################### R> ### chunk number 16: plot1 eval=FALSE R> ################################################### R> ## plot(Z) R> R> R> ################################################### R> ### chunk number 17: plot2 eval=FALSE R> ################################################### R> ## plot(Z, plot.type = "single", col = 2:4) R> R> R> ################################################### R> ### chunk number 18: plot2-repeat R> ################################################### R> plot(Z, plot.type = "single", col = 2:4) R> R> R> ################################################### R> ### chunk number 19: plot1-repeat R> ################################################### R> plot(Z) R> R> R> ################################################### R> ### chunk number 20: plot3 R> ################################################### R> plot(Z, type = "b", lty = 1:3, pch = list(Aa = 1:5, Bb = 2, Cc = 4), col = list(Bb = 2, 4)) R> R> R> ################################################### R> ### chunk number 21: plot3-repeat eval=FALSE R> ################################################### R> ## plot(Z, type = "b", lty = 1:3, pch = list(Aa = 1:5, Bb = 2, Cc = 4), col = list(Bb = 2, 4)) R> R> R> ################################################### R> ### chunk number 22: rbind R> ################################################### R> rbind(z1[5:10], z1[2:3]) 2004-01-14 2004-01-19 2004-01-27 2004-02-07 2004-02-12 2004-02-16 0.02107873 -0.29823529 1.94078850 1.27384445 0.22170438 -2.07607585 2004-02-20 2004-02-24 -1.78439244 -0.19533304 R> R> R> ################################################### R> ### chunk number 23: cbind R> ################################################### R> cbind(z1, z2) z1 z2 2004-01-03 NA 0.94306673 2004-01-05 0.74675994 -0.04149429 2004-01-14 0.02107873 NA 2004-01-17 NA 0.59448077 2004-01-19 -0.29823529 -0.52575918 2004-01-24 NA -0.96739776 2004-01-25 0.68625772 NA 2004-01-27 1.94078850 NA 2004-02-07 1.27384445 NA 2004-02-08 NA 0.95605566 2004-02-12 0.22170438 -0.62733473 2004-02-13 NA -0.92845336 2004-02-16 -2.07607585 NA 2004-02-20 -1.78439244 NA 2004-02-24 -0.19533304 NA 2004-02-25 NA 0.56060280 2004-02-26 NA 0.08291711 R> R> R> ################################################### R> ### chunk number 24: merge R> ################################################### R> merge(z1, z2, all = FALSE) z1 z2 2004-01-05 0.7467599 -0.04149429 2004-01-19 -0.2982353 -0.52575918 2004-02-12 0.2217044 -0.62733473 R> R> R> ################################################### R> ### chunk number 25: merge2 R> ################################################### R> merge(z1, pi, 1:10) z1 pi 1:10 2004-01-05 0.74675994 3.141593 1 2004-01-14 0.02107873 3.141593 2 2004-01-19 -0.29823529 3.141593 3 2004-01-25 0.68625772 3.141593 4 2004-01-27 1.94078850 3.141593 5 2004-02-07 1.27384445 3.141593 6 2004-02-12 0.22170438 3.141593 7 2004-02-16 -2.07607585 3.141593 8 2004-02-20 -1.78439244 3.141593 9 2004-02-24 -0.19533304 3.141593 10 R> R> R> ################################################### R> ### chunk number 26: aggregate R> ################################################### R> firstofmonth <- function(x) as.Date(sub("..$", "01", format(x))) R> aggregate(Z, firstofmonth(index(Z)), mean) Aa Bb Cc 2004-02-01 -0.1377964 0.40676219 -0.2376514 2004-03-01 -0.1667933 0.03905223 -0.2870087 R> aggregate(Z, firstofmonth, head, 1) Aa Bb Cc 2004-02-01 1.255434 0.6815732 -0.6329205 2004-03-01 -1.208610 1.4237978 -0.8161448 R> R> R> ################################################### R> ### chunk number 27: disaggregate R> ################################################### R> Nile.na <- merge(as.zoo(Nile), zoo(, seq(start(Nile)[1], end(Nile)[1], 1/4))) R> head(as.zoo(Nile)) 1871 1872 1873 1874 1875 1876 1120 1160 963 1210 1160 1160 R> head(na.approx(Nile.na)) 1871(1) 1871(2) 1871(3) 1871(4) 1872(1) 1872(2) 1120.00 1130.00 1140.00 1150.00 1160.00 1110.75 R> head(na.locf(Nile.na)) 1871(1) 1871(2) 1871(3) 1871(4) 1872(1) 1872(2) 1120 1120 1120 1120 1160 1160 R> head(na.spline(Nile.na)) 1871(1) 1871(2) 1871(3) 1871(4) 1872(1) 1872(2) 1120.000 1199.059 1224.985 1208.419 1160.000 1091.970 R> R> R> ################################################### R> ### chunk number 28: Ops R> ################################################### R> z1 + z2 2004-01-05 2004-01-19 2004-02-12 0.7052657 -0.8239945 -0.4056304 R> z1 < z2 2004-01-05 2004-01-19 2004-02-12 FALSE FALSE FALSE R> R> R> ################################################### R> ### chunk number 29: cumsum R> ################################################### R> cumsum(Z) Aa Bb Cc 2004-02-02 1.2554339 0.6815732 -0.6329205 2004-02-08 -0.2391494 2.0049854 -2.1273432 2004-02-09 -2.1137718 1.1316925 -1.5000035 2004-02-21 -2.2591579 1.5840415 -1.6459775 2004-02-22 -2.0337337 2.1224309 -1.4146162 2004-02-29 -0.8267785 2.4405731 -1.4259082 2004-03-05 -2.0353888 3.8643710 -2.2420530 2004-03-10 -2.1457844 5.2121135 -1.2868283 2004-03-14 -1.3037606 2.4736933 -1.0553214 2004-03-20 -1.4939516 2.5967820 -2.5739429 R> R> R> ################################################### R> ### chunk number 30: coredata R> ################################################### R> coredata(z1) [1] 0.74675994 0.02107873 -0.29823529 0.68625772 1.94078850 1.27384445 [7] 0.22170438 -2.07607585 -1.78439244 -0.19533304 R> coredata(z1) <- 1:10 R> z1 2004-01-05 2004-01-14 2004-01-19 2004-01-25 2004-01-27 2004-02-07 2004-02-12 1 2 3 4 5 6 7 2004-02-16 2004-02-20 2004-02-24 8 9 10 R> R> R> ################################################### R> ### chunk number 31: index R> ################################################### R> index(z2) [1] "2004-01-03 GMT" "2004-01-05 GMT" "2004-01-17 GMT" "2004-01-19 GMT" [5] "2004-01-24 GMT" "2004-02-08 GMT" "2004-02-12 GMT" "2004-02-13 GMT" [9] "2004-02-25 GMT" "2004-02-26 GMT" R> R> R> ################################################### R> ### chunk number 32: index2 R> ################################################### R> index(z2) <- index(z1) R> z2 2004-01-05 2004-01-14 2004-01-19 2004-01-25 2004-01-27 2004-02-07 0.94306673 -0.04149429 0.59448077 -0.52575918 -0.96739776 0.95605566 2004-02-12 2004-02-16 2004-02-20 2004-02-24 -0.62733473 -0.92845336 0.56060280 0.08291711 R> R> R> ################################################### R> ### chunk number 33: startend R> ################################################### R> start(z1) [1] "2004-01-05 GMT" R> end(z1) [1] "2004-02-24 GMT" R> R> R> ################################################### R> ### chunk number 34: window R> ################################################### R> window(Z, start = as.Date("2004-03-01")) Aa Bb Cc 2004-03-05 -1.2086102 1.4237978 -0.8161448 2004-03-10 -0.1103956 1.3477425 0.9552247 2004-03-14 0.8420238 -2.7384202 0.2315069 2004-03-20 -0.1901910 0.1230887 -1.5186216 R> window(Z, index = index(Z)[5:8], end = as.Date("2004-03-01")) Aa Bb Cc 2004-02-22 0.2254242 0.5383894 0.23136133 2004-02-29 1.2069552 0.3181422 -0.01129202 R> R> R> ################################################### R> ### chunk number 35: window2 R> ################################################### R> window(z1, end = as.POSIXct("2004-02-01")) <- 9:5 R> z1 2004-01-05 2004-01-14 2004-01-19 2004-01-25 2004-01-27 2004-02-07 2004-02-12 9 8 7 6 5 6 7 2004-02-16 2004-02-20 2004-02-24 8 9 10 R> R> R> ################################################### R> ### chunk number 36: lagdiff R> ################################################### R> lag(z1, k = -1) 2004-01-14 2004-01-19 2004-01-25 2004-01-27 2004-02-07 2004-02-12 2004-02-16 9 8 7 6 5 6 7 2004-02-20 2004-02-24 8 9 R> merge(z1, lag(z1, k = 1)) z1 lag(z1, k = 1) 2004-01-05 9 8 2004-01-14 8 7 2004-01-19 7 6 2004-01-25 6 5 2004-01-27 5 6 2004-02-07 6 7 2004-02-12 7 8 2004-02-16 8 9 2004-02-20 9 10 2004-02-24 10 NA R> diff(z1) 2004-01-14 2004-01-19 2004-01-25 2004-01-27 2004-02-07 2004-02-12 2004-02-16 -1 -1 -1 -1 1 1 1 2004-02-20 2004-02-24 1 1 R> R> R> ################################################### R> ### chunk number 37: coercion R> ################################################### R> as.data.frame(Z) Aa Bb Cc 2004-02-02 1.2554339 0.6815732 -0.63292049 2004-02-08 -1.4945833 1.3234122 -1.49442269 2004-02-09 -1.8746225 -0.8732929 0.62733971 2004-02-21 -0.1453861 0.4523490 -0.14597401 2004-02-22 0.2254242 0.5383894 0.23136133 2004-02-29 1.2069552 0.3181422 -0.01129202 2004-03-05 -1.2086102 1.4237978 -0.81614483 2004-03-10 -0.1103956 1.3477425 0.95522468 2004-03-14 0.8420238 -2.7384202 0.23150695 2004-03-20 -0.1901910 0.1230887 -1.51862157 R> R> R> ################################################### R> ### chunk number 38: na R> ################################################### R> z1[sample(1:10, 3)] <- NA R> z1 2004-01-05 2004-01-14 2004-01-19 2004-01-25 2004-01-27 2004-02-07 2004-02-12 9 NA 7 6 5 6 NA 2004-02-16 2004-02-20 2004-02-24 8 9 NA R> na.omit(z1) 2004-01-05 2004-01-19 2004-01-25 2004-01-27 2004-02-07 2004-02-16 2004-02-20 9 7 6 5 6 8 9 R> na.contiguous(z1) 2004-01-19 2004-01-25 2004-01-27 2004-02-07 7 6 5 6 R> na.approx(z1) 2004-01-05 2004-01-14 2004-01-19 2004-01-25 2004-01-27 2004-02-07 2004-02-12 9.000000 7.714286 7.000000 6.000000 5.000000 6.000000 7.111111 2004-02-16 2004-02-20 8.000000 9.000000 R> na.approx(z1, 1:NROW(z1)) 2004-01-05 2004-01-14 2004-01-19 2004-01-25 2004-01-27 2004-02-07 2004-02-12 9 8 7 6 5 6 7 2004-02-16 2004-02-20 8 9 R> na.locf(z1) 2004-01-05 2004-01-14 2004-01-19 2004-01-25 2004-01-27 2004-02-07 2004-02-12 9 9 7 6 5 6 6 2004-02-16 2004-02-20 2004-02-24 8 9 9 R> R> R> ################################################### R> ### chunk number 39: rollapply R> ################################################### R> rollapply(Z, 5, sd) Aa Bb Cc 2004-02-09 1.2814876 0.8018950 0.8218959 2004-02-21 1.2658555 0.7891358 0.8025043 2004-02-22 1.2102011 0.8206819 0.5319727 2004-02-29 0.8662296 0.5266261 0.6411751 2004-03-05 0.9363400 1.7011273 0.6356144 2004-03-10 0.9508642 1.6892246 0.9578196 R> rollapply(Z, 5, sd, fill = NA, align = "left") Aa Bb Cc 2004-02-02 1.2814876 0.8018950 0.8218959 2004-02-08 1.2658555 0.7891358 0.8025043 2004-02-09 1.2102011 0.8206819 0.5319727 2004-02-21 0.8662296 0.5266261 0.6411751 2004-02-22 0.9363400 1.7011273 0.6356144 2004-02-29 0.9508642 1.6892246 0.9578196 2004-03-05 NA NA NA 2004-03-10 NA NA NA 2004-03-14 NA NA NA 2004-03-20 NA NA NA R> R> R> ################################################### R> ### chunk number 40: rollmean R> ################################################### R> rollmean(z2, 5, fill = NA) 2004-01-05 2004-01-14 2004-01-19 2004-01-25 2004-01-27 NA NA 0.0005792538 0.0031770388 -0.1139910497 2004-02-07 2004-02-12 2004-02-16 2004-02-20 2004-02-24 -0.4185778750 -0.2013054791 0.0087574946 NA NA R> R> R> ################################################### R> ### chunk number 41: strucchange1 R> ################################################### R> library("strucchange") R> library("DAAG") Loading required package: MASS Loading required package: lattice Loading required package: latticeExtra Loading required package: RColorBrewer Loading required package: rpart Loading required package: randomForest randomForest 4.6-7 Type rfNews() to see new features/changes/bug fixes. Loading required package: boot Attaching package: 'boot' The following object is masked from 'package:lattice': melanoma Loading required package: survival Loading required package: splines Attaching package: 'survival' The following object is masked from 'package:boot': aml Attaching package: 'DAAG' The following object is masked from 'package:survival': lung The following object is masked from 'package:MASS': hills R> data("fruitohms") R> ocus <- gefp(ohms ~ 1, order.by = ~ juice, data = fruitohms) R> R> R> ################################################### R> ### chunk number 42: strucchange2 R> ################################################### R> plot(ocus) R> R> R> ################################################### R> ### chunk number 43: tseries1 eval=FALSE R> ################################################### R> ## library("tseries") R> ## MSFT <- get.hist.quote(instrument = "MSFT", start = "2001-01-01", R> ## end = "2004-09-30", origin = "1970-01-01", retclass = "ts") R> R> R> ################################################### R> ### chunk number 44: tseries1a R> ################################################### R> if(online) { + MSFT <- get.hist.quote("MSFT", start = "2001-01-01", + end = "2004-09-30", origin = "1970-01-01", retclass = "ts") + save(MSFT, file = "MSFT.rda", compress = TRUE) + } else { + load(system.file("doc", "MSFT.rda", package = "zoo")) + } R> R> R> ################################################### R> ### chunk number 45: tseries2 R> ################################################### R> MSFT <- as.zoo(MSFT) R> index(MSFT) <- as.Date(index(MSFT)) R> MSFT <- na.omit(MSFT) R> R> R> ################################################### R> ### chunk number 46: tseries3 R> ################################################### R> MSFT <- as.zoo(MSFT) R> R> R> ################################################### R> ### chunk number 47: tseries3 R> ################################################### R> plot(diff(log(MSFT))) R> R> R> ################################################### R> ### chunk number 48: timeDate2 R> ################################################### R> library("timeDate") R> z2td <- zoo(coredata(z2), timeDate(index(z2), FinCenter = "GMT")) R> z2td 2004-01-05 2004-01-14 2004-01-19 2004-01-25 2004-01-27 2004-02-07 0.94306673 -0.04149429 0.59448077 -0.52575918 -0.96739776 0.95605566 2004-02-12 2004-02-16 2004-02-20 2004-02-24 -0.62733473 -0.92845336 0.56060280 0.08291711 R> R> R> ################################################### R> ### chunk number 49: yearmon1 R> ################################################### R> zr3 <- zooreg(rnorm(9), start = as.yearmon(2000), frequency = 12) R> zr3 Jan 2000 Feb 2000 Mar 2000 Apr 2000 May 2000 Jun 2000 -0.30969096 0.08699142 -0.64837101 -0.62786277 -0.61932674 -0.95506154 Jul 2000 Aug 2000 Sep 2000 -1.91736406 0.38108885 1.51405511 R> R> R> ################################################### R> ### chunk number 50: yearmon2 R> ################################################### R> aggregate(zr3, as.yearqtr, mean) 2000 Q1 2000 Q2 2000 Q3 -0.2903569 -0.7340837 -0.0074067 R> R> R> ################################################### R> ### chunk number 51: yearmon3 R> ################################################### R> as.Date(index(zr3)) [1] "2000-01-01" "2000-02-01" "2000-03-01" "2000-04-01" "2000-05-01" [6] "2000-06-01" "2000-07-01" "2000-08-01" "2000-09-01" R> as.Date(index(zr3), frac = 1) [1] "2000-01-31" "2000-02-29" "2000-03-31" "2000-04-30" "2000-05-31" [6] "2000-06-30" "2000-07-31" "2000-08-31" "2000-09-30" R> R> R> ################################################### R> ### chunk number 52: yearmon4 R> ################################################### R> index(zr3) <- as.POSIXct(index(zr3)) R> as.irts(zr3) 2000-01-01 00:00:00 GMT -0.3097 2000-02-01 00:00:00 GMT 0.08699 2000-03-01 00:00:00 GMT -0.6484 2000-04-01 00:00:00 GMT -0.6279 2000-05-01 00:00:00 GMT -0.6193 2000-06-01 00:00:00 GMT -0.9551 2000-07-01 00:00:00 GMT -1.917 2000-08-01 00:00:00 GMT 0.3811 2000-09-01 00:00:00 GMT 1.514 R> R> R> > proc.time() user system elapsed 2.520 0.096 2.611 zoo/tests/vignette-zoo.R0000644000175400001440000002424711652760524015214 0ustar zeileisusers################################################### ### chunk number 1: preliminaries ################################################### library("zoo") library("tseries") library("strucchange") library("timeDate") online <- FALSE ## if set to FALSE the local copy of MSFT.rda ## is used instead of get.hist.quote() options(prompt = "R> ") Sys.setenv(TZ = "GMT") ################################################### ### chunk number 2: zoo-prelim ################################################### library("zoo") set.seed(1071) ################################################### ### chunk number 3: zoo-vectors1 ################################################### z1.index <- ISOdatetime(2004, rep(1:2,5), sample(28,10), 0, 0, 0) z1.data <- rnorm(10) z1 <- zoo(z1.data, z1.index) ################################################### ### chunk number 4: zoo-vectors2 ################################################### z2.index <- as.POSIXct(paste(2004, rep(1:2, 5), sample(1:28, 10), sep = "-")) z2.data <- sin(2*1:10/pi) z2 <- zoo(z2.data, z2.index) ################################################### ### chunk number 5: zoo-matrix ################################################### Z.index <- as.Date(sample(12450:12500, 10)) Z.data <- matrix(rnorm(30), ncol = 3) colnames(Z.data) <- c("Aa", "Bb", "Cc") Z <- zoo(Z.data, Z.index) ################################################### ### chunk number 6: print1 ################################################### z1 z1[3:7] ################################################### ### chunk number 7: print2 ################################################### Z Z[1:3, 2:3] ################################################### ### chunk number 8: subset ################################################### z1[ISOdatetime(2004, 1, c(14, 25), 0, 0, 0)] ################################################### ### chunk number 9: summary ################################################### summary(z1) summary(Z) ################################################### ### chunk number 10: zooreg1 ################################################### zr1 <- zooreg(sin(1:9), start = 2000, frequency = 4) zr2 <- zoo(sin(1:9), seq(2000, 2002, by = 1/4), 4) zr1 zr2 ################################################### ### chunk number 11: zooreg2 ################################################### zr1 <- zr1[-c(3, 5)] zr1 class(zr1) frequency(zr1) ################################################### ### chunk number 12: zooreg1b ################################################### zooreg(1:5, start = as.Date("2005-01-01")) ################################################### ### chunk number 13: zooreg3 ################################################### is.regular(zr1) is.regular(zr1, strict = TRUE) ################################################### ### chunk number 14: zooreg4 ################################################### zr1 <- as.zoo(zr1) zr1 class(zr1) is.regular(zr1) frequency(zr1) ################################################### ### chunk number 15: zooreg5 ################################################### as.ts(zr1) identical(zr2, as.zoo(as.ts(zr2))) ################################################### ### chunk number 16: plot1 eval=FALSE ################################################### ## plot(Z) ################################################### ### chunk number 17: plot2 eval=FALSE ################################################### ## plot(Z, plot.type = "single", col = 2:4) ################################################### ### chunk number 18: plot2-repeat ################################################### plot(Z, plot.type = "single", col = 2:4) ################################################### ### chunk number 19: plot1-repeat ################################################### plot(Z) ################################################### ### chunk number 20: plot3 ################################################### plot(Z, type = "b", lty = 1:3, pch = list(Aa = 1:5, Bb = 2, Cc = 4), col = list(Bb = 2, 4)) ################################################### ### chunk number 21: plot3-repeat eval=FALSE ################################################### ## plot(Z, type = "b", lty = 1:3, pch = list(Aa = 1:5, Bb = 2, Cc = 4), col = list(Bb = 2, 4)) ################################################### ### chunk number 22: rbind ################################################### rbind(z1[5:10], z1[2:3]) ################################################### ### chunk number 23: cbind ################################################### cbind(z1, z2) ################################################### ### chunk number 24: merge ################################################### merge(z1, z2, all = FALSE) ################################################### ### chunk number 25: merge2 ################################################### merge(z1, pi, 1:10) ################################################### ### chunk number 26: aggregate ################################################### firstofmonth <- function(x) as.Date(sub("..$", "01", format(x))) aggregate(Z, firstofmonth(index(Z)), mean) aggregate(Z, firstofmonth, head, 1) ################################################### ### chunk number 27: disaggregate ################################################### Nile.na <- merge(as.zoo(Nile), zoo(, seq(start(Nile)[1], end(Nile)[1], 1/4))) head(as.zoo(Nile)) head(na.approx(Nile.na)) head(na.locf(Nile.na)) head(na.spline(Nile.na)) ################################################### ### chunk number 28: Ops ################################################### z1 + z2 z1 < z2 ################################################### ### chunk number 29: cumsum ################################################### cumsum(Z) ################################################### ### chunk number 30: coredata ################################################### coredata(z1) coredata(z1) <- 1:10 z1 ################################################### ### chunk number 31: index ################################################### index(z2) ################################################### ### chunk number 32: index2 ################################################### index(z2) <- index(z1) z2 ################################################### ### chunk number 33: startend ################################################### start(z1) end(z1) ################################################### ### chunk number 34: window ################################################### window(Z, start = as.Date("2004-03-01")) window(Z, index = index(Z)[5:8], end = as.Date("2004-03-01")) ################################################### ### chunk number 35: window2 ################################################### window(z1, end = as.POSIXct("2004-02-01")) <- 9:5 z1 ################################################### ### chunk number 36: lagdiff ################################################### lag(z1, k = -1) merge(z1, lag(z1, k = 1)) diff(z1) ################################################### ### chunk number 37: coercion ################################################### as.data.frame(Z) ################################################### ### chunk number 38: na ################################################### z1[sample(1:10, 3)] <- NA z1 na.omit(z1) na.contiguous(z1) na.approx(z1) na.approx(z1, 1:NROW(z1)) na.locf(z1) ################################################### ### chunk number 39: rollapply ################################################### rollapply(Z, 5, sd) rollapply(Z, 5, sd, fill = NA, align = "left") ################################################### ### chunk number 40: rollmean ################################################### rollmean(z2, 5, fill = NA) ################################################### ### chunk number 41: strucchange1 ################################################### library("strucchange") library("DAAG") data("fruitohms") ocus <- gefp(ohms ~ 1, order.by = ~ juice, data = fruitohms) ################################################### ### chunk number 42: strucchange2 ################################################### plot(ocus) ################################################### ### chunk number 43: tseries1 eval=FALSE ################################################### ## library("tseries") ## MSFT <- get.hist.quote(instrument = "MSFT", start = "2001-01-01", ## end = "2004-09-30", origin = "1970-01-01", retclass = "ts") ################################################### ### chunk number 44: tseries1a ################################################### if(online) { MSFT <- get.hist.quote("MSFT", start = "2001-01-01", end = "2004-09-30", origin = "1970-01-01", retclass = "ts") save(MSFT, file = "MSFT.rda", compress = TRUE) } else { load(system.file("doc", "MSFT.rda", package = "zoo")) } ################################################### ### chunk number 45: tseries2 ################################################### MSFT <- as.zoo(MSFT) index(MSFT) <- as.Date(index(MSFT)) MSFT <- na.omit(MSFT) ################################################### ### chunk number 46: tseries3 ################################################### MSFT <- as.zoo(MSFT) ################################################### ### chunk number 47: tseries3 ################################################### plot(diff(log(MSFT))) ################################################### ### chunk number 48: timeDate2 ################################################### library("timeDate") z2td <- zoo(coredata(z2), timeDate(index(z2), FinCenter = "GMT")) z2td ################################################### ### chunk number 49: yearmon1 ################################################### zr3 <- zooreg(rnorm(9), start = as.yearmon(2000), frequency = 12) zr3 ################################################### ### chunk number 50: yearmon2 ################################################### aggregate(zr3, as.yearqtr, mean) ################################################### ### chunk number 51: yearmon3 ################################################### as.Date(index(zr3)) as.Date(index(zr3), frac = 1) ################################################### ### chunk number 52: yearmon4 ################################################### index(zr3) <- as.POSIXct(index(zr3)) as.irts(zr3) zoo/tests/vignette-zoo-quickref.Rout.save0000644000175400001440000003557212155436226020511 0ustar zeileisusers R version 3.0.0 (2013-04-03) -- "Masked Marvel" Copyright (C) 2013 The R Foundation for Statistical Computing Platform: x86_64-pc-linux-gnu (64-bit) R is free software and comes with ABSOLUTELY NO WARRANTY. You are welcome to redistribute it under certain conditions. Type 'license()' or 'licence()' for distribution details. R is a collaborative project with many contributors. Type 'contributors()' for more information and 'citation()' on how to cite R or R packages in publications. Type 'demo()' for some demos, 'help()' for on-line help, or 'help.start()' for an HTML browser interface to help. Type 'q()' to quit R. > ################################################### > ### chunk number 1: preliminaries > ################################################### > library("zoo") Attaching package: 'zoo' The following object is masked from 'package:base': as.Date, as.Date.numeric > library("tseries") > online <- FALSE ## if set to FALSE the local copy of > ## is used instead of get.hist.quote() > options(prompt = "R> ") R> Sys.setenv(TZ = "GMT") R> R> R> ################################################### R> ### chunk number 2: read.zoo R> ################################################### R> inrusd <- read.zoo(system.file("doc", "demo1.txt", package = "zoo"), sep = "|", format="%d %b %Y") R> R> R> ################################################### R> ### chunk number 3: read.table R> ################################################### R> tmp <- read.table(system.file("doc", "demo2.txt", package = "zoo"), sep = ",") R> z <- zoo(tmp[, 3:4], as.Date(as.character(tmp[, 2]), format="%d %b %Y")) R> colnames(z) <- c("Nifty", "Junior") R> R> R> ################################################### R> ### chunk number 4: extract dates R> ################################################### R> time(z) [1] "2005-02-10" "2005-02-11" "2005-02-14" "2005-02-15" "2005-02-17" [6] "2005-02-18" "2005-02-21" "2005-02-22" "2005-02-23" "2005-02-24" [11] "2005-02-25" "2005-02-28" "2005-03-01" "2005-03-02" "2005-03-03" [16] "2005-03-04" "2005-03-07" "2005-03-08" "2005-03-09" "2005-03-10" R> R> R> ################################################### R> ### chunk number 5: start and end R> ################################################### R> start(z) [1] "2005-02-10" R> end(inrusd) [1] "2005-03-10" R> R> R> ################################################### R> ### chunk number 6: convert to plain matrix R> ################################################### R> plain <- coredata(z) R> str(plain) num [1:20, 1:2] 2063 2082 2098 2090 2062 ... - attr(*, "dimnames")=List of 2 ..$ : NULL ..$ : chr [1:2] "Nifty" "Junior" R> R> R> ################################################### R> ### chunk number 7: intersection R> ################################################### R> m <- merge(inrusd, z, all = FALSE) R> R> R> ################################################### R> ### chunk number 8: union R> ################################################### R> m <- merge(inrusd, z) R> R> R> ################################################### R> ### chunk number 9: merge with lag R> ################################################### R> merge(inrusd, lag(inrusd, -1)) inrusd lag(inrusd, -1) 2005-02-10 43.78 NA 2005-02-11 43.79 43.78 2005-02-14 43.72 43.79 2005-02-15 43.76 43.72 2005-02-16 43.82 43.76 2005-02-17 43.74 43.82 2005-02-18 43.84 43.74 2005-02-21 43.82 43.84 2005-02-22 43.72 43.82 2005-02-23 43.72 43.72 2005-02-24 43.70 43.72 2005-02-25 43.69 43.70 2005-02-28 43.64 43.69 2005-03-01 43.72 43.64 2005-03-02 43.70 43.72 2005-03-03 43.65 43.70 2005-03-04 43.71 43.65 2005-03-07 43.69 43.71 2005-03-09 43.67 43.69 2005-03-10 43.58 43.67 R> R> R> ################################################### R> ### chunk number 10: plotting1 R> ################################################### R> plot(m) R> R> R> ################################################### R> ### chunk number 11: plotting2 R> ################################################### R> plot(m[, 2:3], plot.type = "single", col = c("red", "blue"), lwd = 2) R> R> R> ################################################### R> ### chunk number 12: select range of dates R> ################################################### R> window(z, start = as.Date("2005-02-15"), end = as.Date("2005-02-28")) Nifty Junior 2005-02-15 2089.95 4367.25 2005-02-17 2061.90 4320.15 2005-02-18 2055.55 4318.15 2005-02-21 2043.20 4262.25 2005-02-22 2058.40 4326.10 2005-02-23 2057.10 4346.00 2005-02-24 2055.30 4337.00 2005-02-25 2060.90 4305.75 2005-02-28 2103.25 4388.20 R> R> R> ################################################### R> ### chunk number 13: select one date R> ################################################### R> m[as.Date("2005-03-10")] inrusd Nifty Junior 2005-03-10 43.58 2167.4 4648.05 R> R> R> ################################################### R> ### chunk number 14: impute NAs by interpolation R> ################################################### R> interpolated <- na.approx(m) R> R> R> ################################################### R> ### chunk number 15: impute NAs by LOCF R> ################################################### R> m <- na.locf(m) R> m inrusd Nifty Junior 2005-02-10 43.78 2063.35 4379.20 2005-02-11 43.79 2082.05 4382.90 2005-02-14 43.72 2098.25 4391.15 2005-02-15 43.76 2089.95 4367.25 2005-02-16 43.82 2089.95 4367.25 2005-02-17 43.74 2061.90 4320.15 2005-02-18 43.84 2055.55 4318.15 2005-02-21 43.82 2043.20 4262.25 2005-02-22 43.72 2058.40 4326.10 2005-02-23 43.72 2057.10 4346.00 2005-02-24 43.70 2055.30 4337.00 2005-02-25 43.69 2060.90 4305.75 2005-02-28 43.64 2103.25 4388.20 2005-03-01 43.72 2084.40 4382.25 2005-03-02 43.70 2093.25 4470.00 2005-03-03 43.65 2128.85 4515.80 2005-03-04 43.71 2148.15 4549.55 2005-03-07 43.69 2160.10 4618.05 2005-03-08 43.69 2168.95 4666.70 2005-03-09 43.67 2160.80 4623.85 2005-03-10 43.58 2167.40 4648.05 R> R> R> ################################################### R> ### chunk number 16: compute returns R> ################################################### R> prices2returns <- function(x) 100*diff(log(x)) R> R> R> ################################################### R> ### chunk number 17: column-wise returns R> ################################################### R> r <- prices2returns(m) R> R> R> ################################################### R> ### chunk number 18: rolling standard deviations R> ################################################### R> rollapply(r, 10, sd) inrusd Nifty Junior 2005-02-17 0.14599121 0.6993355 0.7878843 2005-02-18 0.14527421 0.6300543 0.8083622 2005-02-21 0.14115862 0.8949318 1.0412806 2005-02-22 0.15166883 0.9345299 1.0256508 2005-02-23 0.14285470 0.9454103 1.1957959 2005-02-24 0.13607992 0.9453855 1.1210963 2005-02-25 0.11962991 0.9334899 1.1105966 2005-02-28 0.11963193 0.8585071 0.9388661 2005-03-01 0.09716262 0.8569891 0.9131822 2005-03-02 0.09787943 0.8860388 1.0566389 2005-03-03 0.11568119 0.8659890 1.0176645 R> R> R> ################################################### R> ### chunk number 19: last day of month R> ################################################### R> prices2returns(aggregate(m, as.yearmon, tail, 1)) inrusd Nifty Junior Mar 2005 -0.1375831 3.004453 5.752866 R> R> R> ################################################### R> ### chunk number 20: last day of week R> ################################################### R> nextfri <- function(x) 7 * ceiling(as.numeric(x-5+4) / 7) + as.Date(5-4) R> prices2returns(aggregate(na.locf(m), nextfri, tail, 1)) inrusd Nifty Junior 2005-02-18 0.11411618 -1.2809533 -1.4883536 2005-02-25 -0.34273997 0.2599329 -0.2875731 2005-03-04 0.04576659 4.1464226 5.5076988 2005-03-11 -0.29785794 0.8921286 2.1419450 R> R> R> ################################################### R> ### chunk number 21: four second mark R> ################################################### R> zsec <- structure(1:10, index = structure(c(1234760403.968, 1234760403.969, + 1234760403.969, 1234760405.029, 1234760405.029, 1234760405.03, + 1234760405.03, 1234760405.072, 1234760405.073, 1234760405.073 + ), class = c("POSIXt", "POSIXct"), tzone = ""), class = "zoo") R> R> to4sec <- function(x) as.POSIXct(4*ceiling(as.numeric(x)/4), origin = "1970-01-01") R> aggregate(zsec, to4sec, tail, 1) 2009-02-16 05:00:04 2009-02-16 05:00:08 3 10 R> R> R> ################################################### R> ### chunk number 22: one second grid R> ################################################### R> # tmp is zsec with time discretized into one second bins R> tmp <- zsec R> st <- start(tmp) R> Epoch <- st - as.numeric(st) R> time(tmp) <- as.integer(time(tmp) + 1e-7) + Epoch R> R> # find index of last value in each one second interval R> ix <- !duplicated(time(tmp), fromLast = TRUE) R> R> # merge with grid R> merge(tmp[ix], zoo(, seq(start(tmp), end(tmp), "sec"))) 2009-02-16 05:00:03 2009-02-16 05:00:04 2009-02-16 05:00:05 3 NA 10 R> R> # Here is a function which generalizes the above: R> R> intraday.discretise <- function(b, Nsec) { + st <- start(b) + time(b) <- Nsec * as.integer(time(b)+1e-7) %/% Nsec + st - + as.numeric(st) + ix <- !duplicated(time(b), fromLast = TRUE) + merge(b[ix], zoo(, seq(start(b), end(b), paste(Nsec, "sec")))) + } R> R> intraday.discretise(zsec, 1) 2009-02-16 05:00:03 2009-02-16 05:00:04 2009-02-16 05:00:05 3 NA 10 R> R> R> R> ################################################### R> ### chunk number 23: tseries R> ################################################### R> library("tseries") R> R> R> ################################################### R> ### chunk number 24: data handling if offline R> ################################################### R> if(online) { + sunw <- get.hist.quote(instrument = "SUNW", start = "2004-01-01", end = "2004-12-31") + sunw2 <- get.hist.quote(instrument = "SUNW", start = "2004-01-01", end = "2004-12-31", + compression = "m", quote = "Close") + eur.usd <- get.hist.quote(instrument = "EUR/USD", provider = "oanda", start = "2004-01-01", end = "2004-12-31") + save(sunw, sunw2, eur.usd, file = "sunw.rda") + } else { + load(system.file("doc", "sunw.rda", package = "zoo")) + } R> R> R> ################################################### R> ### chunk number 25: get.hist.quote daily series eval=FALSE R> ################################################### R> ## sunw <- get.hist.quote(instrument = "SUNW", start = "2004-01-01", end = "2004-12-31") R> R> R> ################################################### R> ### chunk number 26: get.hist.quote monthly series eval=FALSE R> ################################################### R> ## sunw2 <- get.hist.quote(instrument = "SUNW", start = "2004-01-01", end = "2004-12-31", R> ## compression = "m", quote = "Close") R> R> R> ################################################### R> ### chunk number 27: change index to yearmon R> ################################################### R> time(sunw2) <- as.yearmon(time(sunw2)) R> R> R> ################################################### R> ### chunk number 28: compute same series via aggregate R> ################################################### R> sunw3 <- aggregate(sunw[, "Close"], as.yearmon, tail, 1) R> R> R> ################################################### R> ### chunk number 29: compute returns R> ################################################### R> r <- prices2returns(sunw3) R> R> R> ################################################### R> ### chunk number 30: get.hist.quote oanda eval=FALSE R> ################################################### R> ## eur.usd <- get.hist.quote(instrument = "EUR/USD", provider = "oanda", start = "2004-01-01", end = "2004-12-31") R> R> R> ################################################### R> ### chunk number 31: is.weekend convenience function R> ################################################### R> is.weekend <- function(x) ((as.numeric(x)-2) %% 7) < 2 R> R> R> ################################################### R> ### chunk number 32: omit weekends R> ################################################### R> eur.usd <- eur.usd[!is.weekend(time(eur.usd))] R> R> R> ################################################### R> ### chunk number 33: is.weekend based on POSIXlt R> ################################################### R> is.weekend <- function(x) { + x <- as.POSIXlt(x) + x$wday > 5 | x$wday < 1 + } R> R> R> ################################################### R> ### chunk number 34: summaries R> ################################################### R> date1 <- seq(as.Date("2001-01-01"), as.Date("2002-12-1"), by = "day") R> len1 <- length(date1) R> set.seed(1) # to make it reproducible R> data1 <- zoo(rnorm(len1), date1) R> R> # quarterly summary R> R> data1q.mean <- aggregate(data1, as.yearqtr, mean) R> data1q.sd <- aggregate(data1, as.yearqtr, sd) R> head(cbind(mean = data1q.mean, sd = data1q.sd), main = "Quarterly") mean sd 2001 Q1 0.108503596 0.8861821 2001 Q2 -0.006836172 0.9800027 2001 Q3 -0.042260559 0.9954100 2001 Q4 0.096188411 1.0336234 2002 Q1 -0.092684201 1.0337850 2002 Q2 0.049217429 1.0860119 R> R> # weekly summary - week ends on tuesday R> R> # Given a date find the next Tuesday. R> # Based on formula in Prices and Returns section. R> nexttue <- function(x) 7 * ceiling(as.numeric(x - 2 + 4)/7) + as.Date(2 - 4) R> R> data1w <- cbind( + mean = aggregate(data1, nexttue, mean), + sd = aggregate(data1, nexttue, sd) + ) R> head(data1w) mean sd 2001-01-02 -0.22140524 0.5728252 2001-01-09 0.29574667 0.8686111 2001-01-16 -0.02281531 1.2305420 2001-01-23 0.58834959 0.3993624 2001-01-30 -0.44463015 0.9619139 2001-02-06 -0.08522653 0.8349544 R> R> ### ALTERNATIVE ### R> R> # Create function ag like aggregate but takes vector of R> # function names. R> R> FUNs <- c(mean, sd) R> ag <- function(z, by, FUNs) { + f <- function(f) aggregate(z, by, f) + do.call(cbind, sapply(FUNs, f, simplify = FALSE)) + } R> R> data1q <- ag(data1, as.yearqtr, c("mean", "sd")) R> data1w <- ag(data1, nexttue, c("mean", "sd")) R> R> head(data1q) mean sd 2001 Q1 0.108503596 0.8861821 2001 Q2 -0.006836172 0.9800027 2001 Q3 -0.042260559 0.9954100 2001 Q4 0.096188411 1.0336234 2002 Q1 -0.092684201 1.0337850 2002 Q2 0.049217429 1.0860119 R> head(data1w) mean sd 2001-01-02 -0.22140524 0.5728252 2001-01-09 0.29574667 0.8686111 2001-01-16 -0.02281531 1.2305420 2001-01-23 0.58834959 0.3993624 2001-01-30 -0.44463015 0.9619139 2001-02-06 -0.08522653 0.8349544 R> R> R> > proc.time() user system elapsed 1.116 0.052 1.163 zoo/tests/vignette-zoo-quickref.R0000644000175400001440000002213211606607326017011 0ustar zeileisusers################################################### ### chunk number 1: preliminaries ################################################### library("zoo") library("tseries") online <- FALSE ## if set to FALSE the local copy of ## is used instead of get.hist.quote() options(prompt = "R> ") Sys.setenv(TZ = "GMT") ################################################### ### chunk number 2: read.zoo ################################################### inrusd <- read.zoo(system.file("doc", "demo1.txt", package = "zoo"), sep = "|", format="%d %b %Y") ################################################### ### chunk number 3: read.table ################################################### tmp <- read.table(system.file("doc", "demo2.txt", package = "zoo"), sep = ",") z <- zoo(tmp[, 3:4], as.Date(as.character(tmp[, 2]), format="%d %b %Y")) colnames(z) <- c("Nifty", "Junior") ################################################### ### chunk number 4: extract dates ################################################### time(z) ################################################### ### chunk number 5: start and end ################################################### start(z) end(inrusd) ################################################### ### chunk number 6: convert to plain matrix ################################################### plain <- coredata(z) str(plain) ################################################### ### chunk number 7: intersection ################################################### m <- merge(inrusd, z, all = FALSE) ################################################### ### chunk number 8: union ################################################### m <- merge(inrusd, z) ################################################### ### chunk number 9: merge with lag ################################################### merge(inrusd, lag(inrusd, -1)) ################################################### ### chunk number 10: plotting1 ################################################### plot(m) ################################################### ### chunk number 11: plotting2 ################################################### plot(m[, 2:3], plot.type = "single", col = c("red", "blue"), lwd = 2) ################################################### ### chunk number 12: select range of dates ################################################### window(z, start = as.Date("2005-02-15"), end = as.Date("2005-02-28")) ################################################### ### chunk number 13: select one date ################################################### m[as.Date("2005-03-10")] ################################################### ### chunk number 14: impute NAs by interpolation ################################################### interpolated <- na.approx(m) ################################################### ### chunk number 15: impute NAs by LOCF ################################################### m <- na.locf(m) m ################################################### ### chunk number 16: compute returns ################################################### prices2returns <- function(x) 100*diff(log(x)) ################################################### ### chunk number 17: column-wise returns ################################################### r <- prices2returns(m) ################################################### ### chunk number 18: rolling standard deviations ################################################### rollapply(r, 10, sd) ################################################### ### chunk number 19: last day of month ################################################### prices2returns(aggregate(m, as.yearmon, tail, 1)) ################################################### ### chunk number 20: last day of week ################################################### nextfri <- function(x) 7 * ceiling(as.numeric(x-5+4) / 7) + as.Date(5-4) prices2returns(aggregate(na.locf(m), nextfri, tail, 1)) ################################################### ### chunk number 21: four second mark ################################################### zsec <- structure(1:10, index = structure(c(1234760403.968, 1234760403.969, 1234760403.969, 1234760405.029, 1234760405.029, 1234760405.03, 1234760405.03, 1234760405.072, 1234760405.073, 1234760405.073 ), class = c("POSIXt", "POSIXct"), tzone = ""), class = "zoo") to4sec <- function(x) as.POSIXct(4*ceiling(as.numeric(x)/4), origin = "1970-01-01") aggregate(zsec, to4sec, tail, 1) ################################################### ### chunk number 22: one second grid ################################################### # tmp is zsec with time discretized into one second bins tmp <- zsec st <- start(tmp) Epoch <- st - as.numeric(st) time(tmp) <- as.integer(time(tmp) + 1e-7) + Epoch # find index of last value in each one second interval ix <- !duplicated(time(tmp), fromLast = TRUE) # merge with grid merge(tmp[ix], zoo(, seq(start(tmp), end(tmp), "sec"))) # Here is a function which generalizes the above: intraday.discretise <- function(b, Nsec) { st <- start(b) time(b) <- Nsec * as.integer(time(b)+1e-7) %/% Nsec + st - as.numeric(st) ix <- !duplicated(time(b), fromLast = TRUE) merge(b[ix], zoo(, seq(start(b), end(b), paste(Nsec, "sec")))) } intraday.discretise(zsec, 1) ################################################### ### chunk number 23: tseries ################################################### library("tseries") ################################################### ### chunk number 24: data handling if offline ################################################### if(online) { sunw <- get.hist.quote(instrument = "SUNW", start = "2004-01-01", end = "2004-12-31") sunw2 <- get.hist.quote(instrument = "SUNW", start = "2004-01-01", end = "2004-12-31", compression = "m", quote = "Close") eur.usd <- get.hist.quote(instrument = "EUR/USD", provider = "oanda", start = "2004-01-01", end = "2004-12-31") save(sunw, sunw2, eur.usd, file = "sunw.rda") } else { load(system.file("doc", "sunw.rda", package = "zoo")) } ################################################### ### chunk number 25: get.hist.quote daily series eval=FALSE ################################################### ## sunw <- get.hist.quote(instrument = "SUNW", start = "2004-01-01", end = "2004-12-31") ################################################### ### chunk number 26: get.hist.quote monthly series eval=FALSE ################################################### ## sunw2 <- get.hist.quote(instrument = "SUNW", start = "2004-01-01", end = "2004-12-31", ## compression = "m", quote = "Close") ################################################### ### chunk number 27: change index to yearmon ################################################### time(sunw2) <- as.yearmon(time(sunw2)) ################################################### ### chunk number 28: compute same series via aggregate ################################################### sunw3 <- aggregate(sunw[, "Close"], as.yearmon, tail, 1) ################################################### ### chunk number 29: compute returns ################################################### r <- prices2returns(sunw3) ################################################### ### chunk number 30: get.hist.quote oanda eval=FALSE ################################################### ## eur.usd <- get.hist.quote(instrument = "EUR/USD", provider = "oanda", start = "2004-01-01", end = "2004-12-31") ################################################### ### chunk number 31: is.weekend convenience function ################################################### is.weekend <- function(x) ((as.numeric(x)-2) %% 7) < 2 ################################################### ### chunk number 32: omit weekends ################################################### eur.usd <- eur.usd[!is.weekend(time(eur.usd))] ################################################### ### chunk number 33: is.weekend based on POSIXlt ################################################### is.weekend <- function(x) { x <- as.POSIXlt(x) x$wday > 5 | x$wday < 1 } ################################################### ### chunk number 34: summaries ################################################### date1 <- seq(as.Date("2001-01-01"), as.Date("2002-12-1"), by = "day") len1 <- length(date1) set.seed(1) # to make it reproducible data1 <- zoo(rnorm(len1), date1) # quarterly summary data1q.mean <- aggregate(data1, as.yearqtr, mean) data1q.sd <- aggregate(data1, as.yearqtr, sd) head(cbind(mean = data1q.mean, sd = data1q.sd), main = "Quarterly") # weekly summary - week ends on tuesday # Given a date find the next Tuesday. # Based on formula in Prices and Returns section. nexttue <- function(x) 7 * ceiling(as.numeric(x - 2 + 4)/7) + as.Date(2 - 4) data1w <- cbind( mean = aggregate(data1, nexttue, mean), sd = aggregate(data1, nexttue, sd) ) head(data1w) ### ALTERNATIVE ### # Create function ag like aggregate but takes vector of # function names. FUNs <- c(mean, sd) ag <- function(z, by, FUNs) { f <- function(f) aggregate(z, by, f) do.call(cbind, sapply(FUNs, f, simplify = FALSE)) } data1q <- ag(data1, as.yearqtr, c("mean", "sd")) data1w <- ag(data1, nexttue, c("mean", "sd")) head(data1q) head(data1w) zoo/tests/bugfixes.Rout.save0000644000175400001440000000364112155436147016056 0ustar zeileisusers R version 3.0.0 (2013-04-03) -- "Masked Marvel" Copyright (C) 2013 The R Foundation for Statistical Computing Platform: x86_64-pc-linux-gnu (64-bit) R is free software and comes with ABSOLUTELY NO WARRANTY. You are welcome to redistribute it under certain conditions. Type 'license()' or 'licence()' for distribution details. R is a collaborative project with many contributors. Type 'contributors()' for more information and 'citation()' on how to cite R or R packages in publications. Type 'demo()' for some demos, 'help()' for on-line help, or 'help.start()' for an HTML browser interface to help. Type 'q()' to quit R. > ## packages > library("zoo") Attaching package: 'zoo' The following object is masked from 'package:base': as.Date, as.Date.numeric > library("timeDate") > > ## aggregate() with "timeDate" index > z <- zoo(1:3, timeDate(c("2011-09-19 12:00", "2011-09-19 12:00", "2011-09-19 13:00"))) Warning message: In zoo(1:3, timeDate(c("2011-09-19 12:00", "2011-09-19 12:00", "2011-09-19 13:00"))) : some methods for "zoo" objects do not work if the index entries in 'order.by' are not unique > aggregate(z, identity, mean) 2011-09-19 12:00:00 2011-09-19 13:00:00 1.5 3.0 > > ## assignment and preservation of column names in merge() > x <- zoo(cbind(a = 3:4, b = 5:6)) > y <- zoo(1:2) > merge(x, zoo(, time(x))) a b 1 3 5 2 4 6 > merge(y, x) y a b 1 1 3 5 2 2 4 6 > > ## [<-.zoo with logical row index > z <- zoo(cbind(1:5, 11:15), 101:105) > z[index(z) == 103, 1] <- 0 > > ## rollapply(..., mean, partial = TRUE) > z <- zoo(11:15) > identical(rollapply(z, 3, mean, partial = TRUE), + rollapply(z, 3, (mean), partial = TRUE)) [1] TRUE > > ## rollmedian(..., k = 1) > z <- zoo(sin(0:20)) > identical(z, rollmedian(z, 1)) [1] TRUE > identical(coredata(rollmedian(z, 1)), as.vector(runmed(coredata(z), 1))) [1] TRUE > > proc.time() user system elapsed 1.092 0.076 1.162 zoo/tests/bugfixes.R0000644000175400001440000000135012007034041014343 0ustar zeileisusers## packages library("zoo") library("timeDate") ## aggregate() with "timeDate" index z <- zoo(1:3, timeDate(c("2011-09-19 12:00", "2011-09-19 12:00", "2011-09-19 13:00"))) aggregate(z, identity, mean) ## assignment and preservation of column names in merge() x <- zoo(cbind(a = 3:4, b = 5:6)) y <- zoo(1:2) merge(x, zoo(, time(x))) merge(y, x) ## [<-.zoo with logical row index z <- zoo(cbind(1:5, 11:15), 101:105) z[index(z) == 103, 1] <- 0 ## rollapply(..., mean, partial = TRUE) z <- zoo(11:15) identical(rollapply(z, 3, mean, partial = TRUE), rollapply(z, 3, (mean), partial = TRUE)) ## rollmedian(..., k = 1) z <- zoo(sin(0:20)) identical(z, rollmedian(z, 1)) identical(coredata(rollmedian(z, 1)), as.vector(runmed(coredata(z), 1))) zoo/tests/as.Date.Rout.save0000644000175400001440000000637212155436252015522 0ustar zeileisusers R version 3.0.0 (2013-04-03) -- "Masked Marvel" Copyright (C) 2013 The R Foundation for Statistical Computing Platform: x86_64-pc-linux-gnu (64-bit) R is free software and comes with ABSOLUTELY NO WARRANTY. You are welcome to redistribute it under certain conditions. Type 'license()' or 'licence()' for distribution details. R is a collaborative project with many contributors. Type 'contributors()' for more information and 'citation()' on how to cite R or R packages in publications. Type 'demo()' for some demos, 'help()' for on-line help, or 'help.start()' for an HTML browser interface to help. Type 'q()' to quit R. > ## base results > as.Date(10957, origin = "1970-01-01") [1] "2000-01-01" > as.Date("2000-01-01") [1] "2000-01-01" > as.Date(as.POSIXct("2000-01-01 00:00:00 GMT", tz = "GMT")) [1] "2000-01-01" > as.Date(as.POSIXlt("2000-01-01 00:00:00 GMT", tz = "GMT")) [1] "2000-01-01" > as.Date(NA) [1] NA > > ## for chron objects > library("chron") > as.Date(dates("01/01/2000")) [1] "2000-01-01" > as.Date(chron("01/01/2000", "00:00:00")) [1] "2000-01-01" > > ## for tis objects > library("tis") > as.Date(ti(20000101, "daily")) [1] "2000-01-01" > as.Date(jul(20000101)) [1] "2000-01-01" > > ## for timeDate objects > library("timeDate") Attaching package: 'timeDate' The following object is masked from 'package:tis': dayOfWeek, dayOfYear, isHoliday > as.Date(timeDate("2000-01-01")) [1] "2000-01-01" > > ## with zoo attached (masking as.Date/as.Date.numeric) > library("zoo") Attaching package: 'zoo' The following object is masked from 'package:base': as.Date, as.Date.numeric > as.Date(10957) [1] "2000-01-01" > as.Date("2000-01-01") [1] "2000-01-01" > as.Date(as.POSIXct("2000-01-01 00:00:00 GMT", tz = "GMT")) [1] "2000-01-01" > as.Date(as.POSIXlt("2000-01-01 00:00:00 GMT", tz = "GMT")) [1] "2000-01-01" > as.Date(NA) [1] NA > as.Date(yearmon(2000)) [1] "2000-01-01" > as.Date(yearqtr(2000)) [1] "2000-01-01" > as.Date(dates("01/01/2000")) [1] "2000-01-01" > as.Date(chron("01/01/2000", "00:00:00")) [1] "2000-01-01" > as.Date.ti <- tis:::as.Date.ti ## filed request for export > as.Date(ti(20000101, "daily")) [1] "2000-01-01" > as.Date.jul <- tis:::as.Date.jul ## filed request for export > as.Date(jul(20000101)) [1] "2000-01-01" > as.Date.timeDate <- timeDate:::as.Date.timeDate ## filed request for export > as.Date(timeDate("2000-01-01")) [1] "2000-01-01" > > ## with mondate attached (masking again as.Date) > library("mondate") Attaching package: 'mondate' The following object is masked from 'package:tis': day, month, year, ymd > as.Date(10957) [1] "2000-01-01" > as.Date("2000-01-01") [1] "2000-01-01" > as.Date(as.POSIXct("2000-01-01 00:00:00 GMT", tz = "GMT")) [1] "2000-01-01" > as.Date(as.POSIXlt("2000-01-01 00:00:00 GMT", tz = "GMT")) [1] "2000-01-01" > as.Date(NA) [1] NA > as.Date(yearmon(2000)) [1] "2000-01-01" > as.Date(yearqtr(2000)) [1] "2000-01-01" > as.Date(dates("01/01/2000")) [1] "2000-01-01" > as.Date(chron("01/01/2000", "00:00:00")) [1] "2000-01-01" > as.Date(ti(20000101, "daily")) [1] "2000-01-01" > as.Date(jul(20000101)) [1] "2000-01-01" > as.Date(timeDate("2000-01-01")) [1] "2000-01-01" > as.Date(mondate(1/31)) [1] "2000-01-01" > > > proc.time() user system elapsed 1.740 0.060 1.796 zoo/tests/as.Date.R0000644000175400001440000000311311646410727014026 0ustar zeileisusers## base results as.Date(10957, origin = "1970-01-01") as.Date("2000-01-01") as.Date(as.POSIXct("2000-01-01 00:00:00 GMT", tz = "GMT")) as.Date(as.POSIXlt("2000-01-01 00:00:00 GMT", tz = "GMT")) as.Date(NA) ## for chron objects library("chron") as.Date(dates("01/01/2000")) as.Date(chron("01/01/2000", "00:00:00")) ## for tis objects library("tis") as.Date(ti(20000101, "daily")) as.Date(jul(20000101)) ## for timeDate objects library("timeDate") as.Date(timeDate("2000-01-01")) ## with zoo attached (masking as.Date/as.Date.numeric) library("zoo") as.Date(10957) as.Date("2000-01-01") as.Date(as.POSIXct("2000-01-01 00:00:00 GMT", tz = "GMT")) as.Date(as.POSIXlt("2000-01-01 00:00:00 GMT", tz = "GMT")) as.Date(NA) as.Date(yearmon(2000)) as.Date(yearqtr(2000)) as.Date(dates("01/01/2000")) as.Date(chron("01/01/2000", "00:00:00")) as.Date.ti <- tis:::as.Date.ti ## filed request for export as.Date(ti(20000101, "daily")) as.Date.jul <- tis:::as.Date.jul ## filed request for export as.Date(jul(20000101)) as.Date.timeDate <- timeDate:::as.Date.timeDate ## filed request for export as.Date(timeDate("2000-01-01")) ## with mondate attached (masking again as.Date) library("mondate") as.Date(10957) as.Date("2000-01-01") as.Date(as.POSIXct("2000-01-01 00:00:00 GMT", tz = "GMT")) as.Date(as.POSIXlt("2000-01-01 00:00:00 GMT", tz = "GMT")) as.Date(NA) as.Date(yearmon(2000)) as.Date(yearqtr(2000)) as.Date(dates("01/01/2000")) as.Date(chron("01/01/2000", "00:00:00")) as.Date(ti(20000101, "daily")) as.Date(jul(20000101)) as.Date(timeDate("2000-01-01")) as.Date(mondate(1/31)) zoo/tests/Examples/0000755000175400001440000000000012155437504014202 5ustar zeileisuserszoo/tests/Examples/zoo-Ex.Rout.save0000644000175400001440000026742012155437440017205 0ustar zeileisusers R version 3.0.0 (2013-04-03) -- "Masked Marvel" Copyright (C) 2013 The R Foundation for Statistical Computing Platform: x86_64-pc-linux-gnu (64-bit) R is free software and comes with ABSOLUTELY NO WARRANTY. You are welcome to redistribute it under certain conditions. Type 'license()' or 'licence()' for distribution details. R is a collaborative project with many contributors. Type 'contributors()' for more information and 'citation()' on how to cite R or R packages in publications. Type 'demo()' for some demos, 'help()' for on-line help, or 'help.start()' for an HTML browser interface to help. Type 'q()' to quit R. > pkgname <- "zoo" > source(file.path(R.home("share"), "R", "examples-header.R")) > options(warn = 1) > library('zoo') Attaching package: 'zoo' The following object is masked from 'package:base': as.Date, as.Date.numeric > > base::assign(".oldSearch", base::search(), pos = 'CheckExEnv') > cleanEx() > nameEx("MATCH") > ### * MATCH > > flush(stderr()); flush(stdout()) > > ### Name: MATCH > ### Title: Value Matching > ### Aliases: MATCH MATCH.default MATCH.times > ### Keywords: manip > > ### ** Examples > > MATCH(1:5, 2:3) [1] NA 1 2 NA NA > > > > cleanEx() > nameEx("ORDER") > ### * ORDER > > flush(stderr()); flush(stdout()) > > ### Name: ORDER > ### Title: Ordering Permutation > ### Aliases: ORDER ORDER.default > ### Keywords: manip > > ### ** Examples > > ORDER(rnorm(5)) [1] 3 1 2 5 4 > > > > cleanEx() > nameEx("aggregate.zoo") > ### * aggregate.zoo > > flush(stderr()); flush(stdout()) > > ### Name: aggregate.zoo > ### Title: Compute Summary Statistics of zoo Objects > ### Aliases: aggregate.zoo split.zoo > ### Keywords: ts > > ### ** Examples > > ## averaging over values in a month: > # x.date is jan 1,3,5,7; feb 9,11,13; mar 15,17,19 > x.date <- as.Date(paste(2004, rep(1:4, 4:1), seq(1,20,2), sep = "-")); x.date [1] "2004-01-01" "2004-01-03" "2004-01-05" "2004-01-07" "2004-02-09" [6] "2004-02-11" "2004-02-13" "2004-03-15" "2004-03-17" "2004-04-19" > x <- zoo(rnorm(12), x.date); x 2004-01-01 2004-01-03 2004-01-05 2004-01-07 2004-02-09 2004-02-11 2004-02-13 -0.6264538 0.1836433 -0.8356286 1.5952808 0.3295078 -0.8204684 0.4874291 2004-03-15 2004-03-17 2004-04-19 0.7383247 0.5757814 -0.3053884 > # coarser dates - jan 1 (4 times), feb 1 (3 times), mar 1 (3 times) > x.date2 <- as.Date(paste(2004, rep(1:4, 4:1), 1, sep = "-")); x.date2 [1] "2004-01-01" "2004-01-01" "2004-01-01" "2004-01-01" "2004-02-01" [6] "2004-02-01" "2004-02-01" "2004-03-01" "2004-03-01" "2004-04-01" > x2 <- aggregate(x, x.date2, mean); x2 2004-01-01 2004-02-01 2004-03-01 2004-04-01 0.079210426 -0.001177187 0.657053028 -0.305388387 > # same - uses as.yearmon > x2a <- aggregate(x, as.Date(as.yearmon(time(x))), mean); x2a 2004-01-01 2004-02-01 2004-03-01 2004-04-01 0.079210426 -0.001177187 0.657053028 -0.305388387 > # same - uses by function > x2b <- aggregate(x, function(tt) as.Date(as.yearmon(tt)), mean); x2b 2004-01-01 2004-02-01 2004-03-01 2004-04-01 0.079210426 -0.001177187 0.657053028 -0.305388387 > # same - uses cut > x2c <- aggregate(x, as.Date(cut(time(x), "month")), mean); x2c 2004-01-01 2004-02-01 2004-03-01 2004-04-01 0.079210426 -0.001177187 0.657053028 -0.305388387 > # almost same but times of x2d have yearmon class rather than Date class > x2d <- aggregate(x, as.yearmon, mean); x2d Jan 2004 Feb 2004 Mar 2004 Apr 2004 0.079210426 -0.001177187 0.657053028 -0.305388387 > > # compare time series > plot(x) > lines(x2, col = 2) > > ## aggregate a daily time series to a quarterly series > # create zoo series > tt <- as.Date("2000-1-1") + 0:300 > z.day <- zoo(0:300, tt) > > # function which returns corresponding first "Date" of quarter > first.of.quarter <- function(tt) as.Date(as.yearqtr(tt)) > > # average z over quarters > # 1. via "yearqtr" index (regular) > # 2. via "Date" index (not regular) > z.qtr1 <- aggregate(z.day, as.yearqtr, mean) > z.qtr2 <- aggregate(z.day, first.of.quarter, mean) > > # The last one used the first day of the quarter but suppose > # we want the first day of the quarter that exists in the series > # (and the series does not necessarily start on the first day > # of the quarter). > z.day[!duplicated(as.yearqtr(time(z.day)))] 2000-01-01 2000-04-01 2000-07-01 2000-10-01 0 91 182 274 > > # This is the same except it uses the last day of the quarter. > # It requires R 2.6.0 which introduced the fromLast= argument. > ## Not run: > ##D z.day[!duplicated(as.yearqtr(time(z.day)), fromLast = TRUE)] > ## End(Not run) > > # The aggregated series above are of class "zoo" (because z.day > # was "zoo"). To create a regular series of class "zooreg", > # the frequency can be automatically chosen > zr.qtr1 <- aggregate(z.day, as.yearqtr, mean, regular = TRUE) > # or specified explicitely > zr.qtr2 <- aggregate(z.day, as.yearqtr, mean, frequency = 4) > > > ## aggregate on month and extend to monthly time series > if(require(chron)) { + y <- zoo(matrix(11:15, nrow = 5, ncol = 2), chron(c(15, 20, 80, 100, 110))) + colnames(y) <- c("A", "B") + + # aggregate by month using first of month as times for coarser series + # using first day of month as repesentative time + y2 <- aggregate(y, as.Date(as.yearmon(time(y))), head, 1) + + # fill in missing months by merging with an empty series containing + # a complete set of 1st of the months + yrt2 <- range(time(y2)) + y0 <- zoo(,seq(from = yrt2[1], to = yrt2[2], by = "month")) + merge(y2, y0) + } Loading required package: chron A B 1970-01-01 11 11 1970-02-01 NA NA 1970-03-01 13 13 1970-04-01 14 14 > > # given daily series keep only first point in each month at > # day 21 or more > z <- zoo(101:200, as.Date("2000-01-01") + seq(0, length = 100, by = 2)) > zz <- z[as.numeric(format(time(z), "%d")) >= 21] > zz[!duplicated(as.yearmon(time(zz)))] 2000-01-21 2000-02-22 2000-03-21 2000-04-22 2000-05-22 2000-06-21 111 127 141 157 172 187 > > # same except times are of "yearmon" class > aggregate(zz, as.yearmon, head, 1) Jan 2000 Feb 2000 Mar 2000 Apr 2000 May 2000 Jun 2000 111 127 141 157 172 187 > > # aggregate POSIXct seconds data every 10 minutes > tt <- seq(10, 2000, 10) > x <- zoo(tt, structure(tt, class = c("POSIXt", "POSIXct"))) > aggregate(x, time(x) - as.numeric(time(x)) %% 600, mean) 1970-01-01 01:00:00 1970-01-01 01:10:00 1970-01-01 01:20:00 1970-01-01 01:30:00 300 895 1495 1900 > > # aggregate weekly series to a series with frequency of 52 per year > set.seed(1) > z <- zooreg(1:100 + rnorm(100), start = as.Date("2001-01-01"), deltat = 7) > > # new.freq() converts dates to a grid of freq points per year > # yd is sequence of dates of firsts of years > # yy is years of the same sequence > # last line interpolates so dates, d, are transformed to year + frac of year > # so first week of 2001 is 2001.0, second week is 2001 + 1/52, third week > # is 2001 + 2/52, etc. > new.freq <- function(d, freq = 52) { + y <- as.Date(cut(range(d), "years")) + c(0, 367) + yd <- seq(y[1], y[2], "year") + yy <- as.numeric(format(yd, "%Y")) + floor(freq * approx(yd, yy, xout = d)$y) / freq + } > > # take last point in each period > aggregate(z, new.freq, tail, 1) 2001(1) 2001(2) 2001(3) 2001(4) 2001(5) 2001(6) 2001(7) 2001(8) 2.183643 2.164371 5.595281 5.329508 5.179532 7.487429 8.738325 9.575781 2001(9) 2001(10) 2001(11) 2001(12) 2001(13) 2001(14) 2001(15) 2001(16) 9.694612 12.511781 12.389843 12.378759 11.785300 16.124931 15.955066 16.983810 2001(17) 2001(18) 2001(19) 2001(20) 2001(21) 2001(22) 2001(23) 2001(24) 18.943836 19.821221 20.593901 21.918977 22.782136 23.074565 22.010648 25.619826 2001(25) 2001(26) 2001(27) 2001(28) 2001(29) 2001(30) 2001(31) 2001(32) 25.943871 26.844204 26.529248 28.521850 30.417942 32.358680 31.897212 33.387672 2001(33) 2001(34) 2001(35) 2001(36) 2001(37) 2001(38) 2001(39) 2001(40) 33.946195 33.622940 35.585005 36.605710 37.940687 40.100025 40.763176 40.835476 2001(41) 2001(42) 2001(43) 2001(44) 2001(45) 2001(46) 2001(47) 2001(48) 41.746638 43.696963 44.556663 44.311244 45.292505 47.364582 48.768533 48.887654 2001(49) 2001(50) 2001(51) 2001(52) 2002(1) 2002(2) 2002(3) 2002(4) 50.881108 51.398106 51.387974 53.341120 52.870637 56.433024 57.980400 56.632779 2002(5) 2002(6) 2002(7) 2002(8) 2002(9) 2002(10) 2002(11) 2002(12) 56.955865 59.569720 59.864945 63.401618 61.960760 63.689739 64.028002 64.256727 2002(13) 2002(14) 2002(15) 2002(16) 2002(17) 2002(18) 2002(19) 2002(20) 66.188792 65.195041 69.465555 69.153253 72.172612 71.475510 71.290054 73.610726 2002(21) 2002(22) 2002(23) 2002(24) 2002(25) 2002(26) 2002(27) 2002(28) 73.065902 73.746367 76.291446 76.556708 78.001105 79.074341 79.410479 80.431331 2002(29) 2002(30) 2002(31) 2002(32) 2002(33) 2002(34) 2002(35) 2002(36) 81.864821 84.178087 82.476433 85.593946 86.332950 88.063100 87.695816 89.370019 2002(37) 2002(38) 2002(39) 2002(40) 2002(41) 2002(42) 2002(43) 2002(44) 90.267099 90.457480 93.207868 94.160403 94.700214 96.586833 96.558486 95.723408 2002(45) 2002(46) 2002(47) 97.426735 97.775387 99.526599 > > # or, take mean of all points in each > aggregate(z, new.freq, mean) 2001(1) 2001(2) 2001(3) 2001(4) 2001(5) 2001(6) 2001(7) 2001(8) 1.278595 2.164371 5.595281 5.329508 5.179532 7.487429 8.738325 9.575781 2001(9) 2001(10) 2001(11) 2001(12) 2001(13) 2001(14) 2001(15) 2001(16) 9.694612 12.511781 12.389843 12.378759 11.785300 16.124931 15.955066 16.983810 2001(17) 2001(18) 2001(19) 2001(20) 2001(21) 2001(22) 2001(23) 2001(24) 18.943836 19.821221 20.593901 21.918977 22.782136 23.074565 22.010648 25.619826 2001(25) 2001(26) 2001(27) 2001(28) 2001(29) 2001(30) 2001(31) 2001(32) 25.943871 26.844204 26.529248 28.521850 30.417942 32.358680 31.897212 33.387672 2001(33) 2001(34) 2001(35) 2001(36) 2001(37) 2001(38) 2001(39) 2001(40) 33.946195 33.622940 35.585005 36.605710 37.940687 40.100025 40.763176 40.835476 2001(41) 2001(42) 2001(43) 2001(44) 2001(45) 2001(46) 2001(47) 2001(48) 41.746638 43.696963 44.556663 44.311244 45.292505 47.364582 48.768533 48.887654 2001(49) 2001(50) 2001(51) 2001(52) 2002(1) 2002(2) 2002(3) 2002(4) 50.881108 51.398106 51.387974 53.341120 52.870637 56.433024 57.980400 56.632779 2002(5) 2002(6) 2002(7) 2002(8) 2002(9) 2002(10) 2002(11) 2002(12) 56.955865 59.569720 59.864945 63.401618 61.960760 63.689739 64.028002 64.256727 2002(13) 2002(14) 2002(15) 2002(16) 2002(17) 2002(18) 2002(19) 2002(20) 66.188792 65.195041 69.465555 69.153253 72.172612 71.475510 71.290054 73.610726 2002(21) 2002(22) 2002(23) 2002(24) 2002(25) 2002(26) 2002(27) 2002(28) 73.065902 73.746367 76.291446 76.556708 78.001105 79.074341 79.410479 80.431331 2002(29) 2002(30) 2002(31) 2002(32) 2002(33) 2002(34) 2002(35) 2002(36) 81.864821 84.178087 82.476433 85.593946 86.332950 88.063100 87.695816 89.370019 2002(37) 2002(38) 2002(39) 2002(40) 2002(41) 2002(42) 2002(43) 2002(44) 90.267099 90.457480 93.207868 94.160403 94.700214 96.586833 96.558486 95.723408 2002(45) 2002(46) 2002(47) 97.426735 97.775387 99.526599 > > # example of taking means in the presence of NAs > z.na <- zooreg(c(1:364, NA), start = as.Date("2001-01-01")) > aggregate(z.na, as.yearqtr, mean, na.rm = TRUE) 2001 Q1 2001 Q2 2001 Q3 2001 Q4 45.5 136.0 227.5 319.0 > > # Find the sd of all days that lie in any Jan, all days that lie in > # any Feb, ..., all days that lie in any Dec (i.e. output is vector with > # 12 components) > aggregate(z, format(time(z), "%m"), sd) 01 02 03 04 05 06 07 08 27.931987 27.985392 27.679111 27.774779 27.328400 27.840695 27.520893 28.058606 09 10 11 12 27.806512 28.066187 27.406884 1.589453 > > > > > cleanEx() detaching 'package:chron' > nameEx("as.zoo") > ### * as.zoo > > flush(stderr()); flush(stdout()) > > ### Name: as.zoo > ### Title: Coercion from and to zoo > ### Aliases: as.zoo as.zoo.default as.zoo.data.frame as.zoo.fts as.zoo.its > ### as.zoo.irts as.zoo.matrix as.zoo.mcmc as.zoo.tis as.zoo.xts > ### as.zoo.zoo as.matrix.zoo as.vector.zoo as.data.frame.zoo as.list.zoo > ### as.list.ts as.zoo.ts as.ts.zoo > ### Keywords: ts > > ### ** Examples > > ## coercion to zoo: > ## default method > as.zoo(rnorm(5)) 1 2 3 4 5 -0.6264538 0.1836433 -0.8356286 1.5952808 0.3295078 > ## method for "ts" objects > as.zoo(ts(rnorm(5), start = 1981, freq = 12)) 1981(1) 1981(2) 1981(3) 1981(4) 1981(5) -0.8204684 0.4874291 0.7383247 0.5757814 -0.3053884 > > ## coercion from zoo: > x.date <- as.POSIXct(paste("2003-", rep(1:4, 4:1), "-", sample(1:28, 10, replace = TRUE), sep = "")) > x <- zoo(matrix(rnorm(24), ncol = 2), x.date) > as.matrix(x) x.1 x.2 2003-01-04 0.82122120 1.35867955 2003-01-06 -0.01619026 -0.47815006 2003-01-19 0.94383621 0.41794156 2003-01-27 -0.04493361 -1.47075238 2003-02-01 0.78213630 -0.05380504 2003-02-08 0.59390132 -0.10278773 2003-02-11 0.91897737 0.38767161 2003-03-11 0.07456498 -1.37705956 2003-03-25 -1.98935170 -0.41499456 2003-04-10 0.61982575 -0.39428995 > as.vector(x) [1] 0.82122120 -0.01619026 0.94383621 -0.04493361 0.78213630 0.59390132 [7] 0.91897737 0.07456498 -1.98935170 0.61982575 1.35867955 -0.47815006 [13] 0.41794156 -1.47075238 -0.05380504 -0.10278773 0.38767161 -1.37705956 [19] -0.41499456 -0.39428995 > as.data.frame(x) x.1 x.2 2003-01-04 0.82122120 1.35867955 2003-01-06 -0.01619026 -0.47815006 2003-01-19 0.94383621 0.41794156 2003-01-27 -0.04493361 -1.47075238 2003-02-01 0.78213630 -0.05380504 2003-02-08 0.59390132 -0.10278773 2003-02-11 0.91897737 0.38767161 2003-03-11 0.07456498 -1.37705956 2003-03-25 -1.98935170 -0.41499456 2003-04-10 0.61982575 -0.39428995 > as.list(x) $x.1 2003-01-04 2003-01-06 2003-01-19 2003-01-27 2003-02-01 2003-02-08 0.82122120 -0.01619026 0.94383621 -0.04493361 0.78213630 0.59390132 2003-02-11 2003-03-11 2003-03-25 2003-04-10 0.91897737 0.07456498 -1.98935170 0.61982575 $x.2 2003-01-04 2003-01-06 2003-01-19 2003-01-27 2003-02-01 2003-02-08 1.35867955 -0.47815006 0.41794156 -1.47075238 -0.05380504 -0.10278773 2003-02-11 2003-03-11 2003-03-25 2003-04-10 0.38767161 -1.37705956 -0.41499456 -0.39428995 > > > > cleanEx() > nameEx("coredata") > ### * coredata > > flush(stderr()); flush(stdout()) > > ### Name: coredata > ### Title: Extracting/Replacing the Core Data of Objects > ### Aliases: coredata coredata.default coredata.zoo coredata.ts > ### coredata.its coredata.irts coredata<- coredata<-.zoo coredata<-.ts > ### coredata<-.irts coredata<-.its > ### Keywords: ts > > ### ** Examples > > x.date <- as.Date(paste(2003, rep(1:4, 4:1), seq(1,20,2), sep = "-")) > x <- zoo(matrix(rnorm(20), ncol = 2), x.date) > > ## the full time series > x 2003-01-01 -0.6264538 1.51178117 2003-01-03 0.1836433 0.38984324 2003-01-05 -0.8356286 -0.62124058 2003-01-07 1.5952808 -2.21469989 2003-02-09 0.3295078 1.12493092 2003-02-11 -0.8204684 -0.04493361 2003-02-13 0.4874291 -0.01619026 2003-03-15 0.7383247 0.94383621 2003-03-17 0.5757814 0.82122120 2003-04-19 -0.3053884 0.59390132 > ## and only matrix of observations > coredata(x) [,1] [,2] [1,] -0.6264538 1.51178117 [2,] 0.1836433 0.38984324 [3,] -0.8356286 -0.62124058 [4,] 1.5952808 -2.21469989 [5,] 0.3295078 1.12493092 [6,] -0.8204684 -0.04493361 [7,] 0.4874291 -0.01619026 [8,] 0.7383247 0.94383621 [9,] 0.5757814 0.82122120 [10,] -0.3053884 0.59390132 > > ## change the observations > coredata(x) <- matrix(1:20, ncol = 2) > x 2003-01-01 1 11 2003-01-03 2 12 2003-01-05 3 13 2003-01-07 4 14 2003-02-09 5 15 2003-02-11 6 16 2003-02-13 7 17 2003-03-15 8 18 2003-03-17 9 19 2003-04-19 10 20 > > > > cleanEx() > nameEx("frequency") > ### * frequency > > flush(stderr()); flush(stdout()) > > ### Name: frequency<- > ### Title: Replacing the Index of Objects > ### Aliases: frequency<- frequency<-.zoo frequency<-.zooreg > ### Keywords: ts > > ### ** Examples > > z <- zooreg(1:5) > z 1 2 3 4 5 1 2 3 4 5 > as.ts(z) Time Series: Start = 1 End = 5 Frequency = 1 [1] 1 2 3 4 5 > frequency(z) <- 3 > z 1(1) 2(1) 3(1) 4(1) 5(1) 1 2 3 4 5 > as.ts(z) Time Series: Start = c(1, 1) End = c(5, 1) Frequency = 3 [1] 1 NA NA 2 NA NA 3 NA NA 4 NA NA 5 > > > > cleanEx() > nameEx("ggplot2.zoo") > ### * ggplot2.zoo > > flush(stderr()); flush(stdout()) > > ### Name: ggplot2.zoo > ### Title: Convenience Functions for Plotting zoo Objects with ggplot2 > ### Aliases: autoplot.zoo fortify.zoo ggplot2.zoo facet_free yearmon_trans > ### yearqtr_trans scale_x_yearmon scale_y_yearmon scale_x_yearqtr > ### scale_y_yearqtr > > ### ** Examples > > if(require("ggplot2") && require("scales")) { + ## example data + x.Date <- as.Date(paste(2003, 02, c(1, 3, 7, 9, 14), sep = "-")) + x <- zoo(rnorm(5), x.Date) + xlow <- x - runif(5) + xhigh <- x + runif(5) + z <- cbind(x, xlow, xhigh) + + ## univariate plotting + autoplot(x) + ## by hand + ggplot(aes(x = Index, y = Value), data = fortify(x, melt = TRUE)) + + geom_line() + xlab("Index") + ylab("x") + ## adding series one at a time + last_plot() + geom_line(aes(x = Index, y = xlow), colour = "red", data = fortify(xlow)) + ## add ribbon for high/low band + ggplot(aes(x = Index, y = x, ymin = xlow, ymax = xhigh), data = fortify(x)) + + geom_ribbon(fill = "darkgray") + geom_line() + + ## multivariate plotting in multiple or single panels + autoplot(z) ## multiple without color/linetype + autoplot(z, facets = Series ~ .) ## multiple with series-dependent color/linetype + autoplot(z, facets = NULL) ## single with series-dependent color/linetype + ## by hand with color/linetype and with/without facets + qplot(x = Index, y = Value, group = Series, colour = Series, + linetype = Series, facets = Series ~ ., data = fortify(z, melt = TRUE)) + + geom_line() + xlab("Index") + ylab("") + ggplot(aes(x = Index, y = Value, group = Series, colour = Series, linetype = Series), + data = fortify(z, melt = TRUE)) + geom_line() + xlab("Index") + ylab("") + ## variations + autoplot(z, geom = "point") + autoplot(z, facets = NULL) + geom_point() + autoplot(z, facets = NULL) + scale_colour_grey() + theme_bw() + + ## for "ts" series via coercion + autoplot(as.zoo(EuStockMarkets)) + autoplot(as.zoo(EuStockMarkets), facets = NULL) + + autoplot(z) + + aes(colour = NULL, linetype = NULL) + + facet_grid(series ~ ., scales = "free_y") + + autoplot(z) + aes(colour = NULL, linetype = NULL) + facet_free() # same + + z.yq <- zooreg(rnorm(50), as.yearqtr("2000-1"), freq = 4) + autoplot(z.yq) + scale_x_yearqtr() + } Loading required package: ggplot2 Loading required package: scales > > > > cleanEx() detaching 'package:scales', 'package:ggplot2' > nameEx("index") > ### * index > > flush(stderr()); flush(stdout()) > > ### Name: index > ### Title: Extracting/Replacing the Index of Objects > ### Aliases: index index.default index.zoo index.ts time.zoo index<- > ### index<-.zoo time<- time<-.zoo start.zoo end.zoo > ### Keywords: ts > > ### ** Examples > > x.date <- as.Date(paste(2003, 2, c(1, 3, 7, 9, 14), sep = "-")) > x <- zoo(rnorm(5), x.date) > > ## query index/time of a zoo object > index(x) [1] "2003-02-01" "2003-02-03" "2003-02-07" "2003-02-09" "2003-02-14" > time(x) [1] "2003-02-01" "2003-02-03" "2003-02-07" "2003-02-09" "2003-02-14" > > ## change class of index from Date to POSIXct > ## relative to current time zone > x 2003-02-01 2003-02-03 2003-02-07 2003-02-09 2003-02-14 -0.6264538 0.1836433 -0.8356286 1.5952808 0.3295078 > index(x) <- as.POSIXct(format(time(x)),tz="") > x 2003-02-01 2003-02-03 2003-02-07 2003-02-09 2003-02-14 -0.6264538 0.1836433 -0.8356286 1.5952808 0.3295078 > > ## replace index/time of a zoo object > index(x) <- 1:5 > x 1 2 3 4 5 -0.6264538 0.1836433 -0.8356286 1.5952808 0.3295078 > time(x) <- 6:10 > x 6 7 8 9 10 -0.6264538 0.1836433 -0.8356286 1.5952808 0.3295078 > > ## query start and end of a zoo object > start(x) [1] 6 > end(x) [1] 10 > > ## query index of a usual matrix > xm <- matrix(rnorm(10), ncol = 2) > index(xm) [1] 1 2 3 4 5 > > > > cleanEx() > nameEx("is.regular") > ### * is.regular > > flush(stderr()); flush(stdout()) > > ### Name: is.regular > ### Title: Check Regularity of a Series > ### Aliases: is.regular is.regular.zoo is.regular.ts is.regular.zooreg > ### is.regular.default > ### Keywords: ts > > ### ** Examples > > ## checking of a strictly regular zoo series > z <- zoo(1:10, seq(2000, 2002.25, by = 0.25), frequency = 4) > z 2000(1) 2000(2) 2000(3) 2000(4) 2001(1) 2001(2) 2001(3) 2001(4) 2002(1) 2002(2) 1 2 3 4 5 6 7 8 9 10 > class(z) [1] "zooreg" "zoo" > frequency(z) ## extraction of frequency attribute [1] 4 > is.regular(z) [1] TRUE > is.regular(z, strict = TRUE) [1] TRUE > ## by omitting observations, the series is not strictly regular > is.regular(z[-3]) [1] TRUE > is.regular(z[-3], strict = TRUE) [1] FALSE > > ## checking of a plain zoo series without frequency attribute > ## which is in fact regular > z <- zoo(1:10, seq(2000, 2002.25, by = 0.25)) > z 2000 2000.25 2000.5 2000.75 2001 2001.25 2001.5 2001.75 2002 2002.25 1 2 3 4 5 6 7 8 9 10 > class(z) [1] "zoo" > frequency(z) ## data driven computation of frequency [1] 4 > is.regular(z) [1] TRUE > is.regular(z, strict = TRUE) [1] TRUE > ## by omitting observations, the series is not strictly regular > is.regular(z[-3]) [1] TRUE > is.regular(z[-3], strict = TRUE) [1] FALSE > > ## checking of an irregular zoo series > z <- zoo(1:10, rnorm(10)) > z -0.8356 -0.8205 -0.6265 -0.3054 0.1836 0.3295 0.4874 0.5758 0.7383 1.5953 3 6 1 10 2 5 7 9 8 4 > class(z) [1] "zoo" > frequency(z) ## attempt of data-driven frequency computation NULL > is.regular(z) [1] FALSE > is.regular(z, strict = TRUE) [1] FALSE > > > > cleanEx() > nameEx("lag.zoo") > ### * lag.zoo > > flush(stderr()); flush(stdout()) > > ### Name: lag.zoo > ### Title: Lags and Differences of zoo Objects > ### Aliases: lag.zoo diff.zoo > ### Keywords: ts > > ### ** Examples > > x <- zoo(11:21) > > lag(x, k = 1) 1 2 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 21 > lag(x, k = -1) 2 3 4 5 6 7 8 9 10 11 11 12 13 14 15 16 17 18 19 20 > # this pairs each value of x with the next or future value > merge(x, lag1 = lag(x, k=1)) x lag1 1 11 12 2 12 13 3 13 14 4 14 15 5 15 16 6 16 17 7 17 18 8 18 19 9 19 20 10 20 21 11 21 NA > diff(x^3) 2 3 4 5 6 7 8 9 10 11 397 469 547 631 721 817 919 1027 1141 1261 > diff(x^3, -1) 1 2 3 4 5 6 7 8 9 10 397 469 547 631 721 817 919 1027 1141 1261 > diff(x^3, na.pad = TRUE) 1 2 3 4 5 6 7 8 9 10 11 NA 397 469 547 631 721 817 919 1027 1141 1261 > > > > > cleanEx() > nameEx("make.par.list") > ### * make.par.list > > flush(stderr()); flush(stdout()) > > ### Name: make.par.list > ### Title: Make a List from a Parameter Specification > ### Aliases: make.par.list > ### Keywords: ts > > ### ** Examples > > make.par.list(letters[1:5], 1:5, 3, 5) $a [1] 1 $b [1] 2 $c [1] 3 $d [1] 4 $e [1] 5 > suppressWarnings( make.par.list(letters[1:5], 1:4, 3, 5, 99) ) $a [1] 1 $b [1] 2 $c [1] 3 $d [1] 4 $e [1] 1 > make.par.list(letters[1:5], c(d=3), 3, 5, 99) $a [1] 99 $b [1] 99 $c [1] 99 $d [1] 3 $e [1] 99 > make.par.list(letters[1:5], list(d=1:2, 99), 3, 5) $a [1] 99 $b [1] 99 $c [1] 99 $d [1] 1 2 1 $e [1] 99 > make.par.list(letters[1:5], list(d=1:2, 99, 100), 3, 5) $a [1] 99 $b [1] 100 $c [1] 99 $d [1] 1 2 1 $e [1] 100 > > > > cleanEx() > nameEx("merge.zoo") > ### * merge.zoo > > flush(stderr()); flush(stdout()) > > ### Name: merge.zoo > ### Title: Merge Two or More zoo Objects > ### Aliases: merge.zoo rbind.zoo c.zoo cbind.zoo > ### Keywords: ts > > ### ** Examples > > ## simple merging > x.date <- as.Date(paste(2003, 02, c(1, 3, 7, 9, 14), sep = "-")) > x <- zoo(rnorm(5), x.date) > > y1 <- zoo(matrix(1:10, ncol = 2), 1:5) > y2 <- zoo(matrix(rnorm(10), ncol = 2), 3:7) > > ## using arguments `fill' and `suffixes' > merge(y1, y2, all = FALSE) y1.1 y1.2 y2.1 y2.2 3 3 8 -0.8204684 1.5117812 4 4 9 0.4874291 0.3898432 5 5 10 0.7383247 -0.6212406 > merge(y1, y2, all = FALSE, suffixes = c("a", "b")) a.1 a.2 b.1 b.2 3 3 8 -0.8204684 1.5117812 4 4 9 0.4874291 0.3898432 5 5 10 0.7383247 -0.6212406 > merge(y1, y2, all = TRUE) y1.1 y1.2 y2.1 y2.2 1 1 6 NA NA 2 2 7 NA NA 3 3 8 -0.8204684 1.5117812 4 4 9 0.4874291 0.3898432 5 5 10 0.7383247 -0.6212406 6 NA NA 0.5757814 -2.2146999 7 NA NA -0.3053884 1.1249309 > merge(y1, y2, all = TRUE, fill = 0) y1.1 y1.2 y2.1 y2.2 1 1 6 0.0000000 0.0000000 2 2 7 0.0000000 0.0000000 3 3 8 -0.8204684 1.5117812 4 4 9 0.4874291 0.3898432 5 5 10 0.7383247 -0.6212406 6 0 0 0.5757814 -2.2146999 7 0 0 -0.3053884 1.1249309 > > ## if different index classes are merged, as in > ## the next merge example then ## a warning is issued and > ### the indexes are coerced. > ## It is up to the user to ensure that the result makes sense. > merge(x, y1, y2, all = TRUE) Warning in merge.zoo(x, y1, y2, all = TRUE) : Index vectors are of different classes: Date integer integer x y1.1 y1.2 y2.1 y2.2 1970-01-02 NA 1 6 NA NA 1970-01-03 NA 2 7 NA NA 1970-01-04 NA 3 8 -0.8204684 1.5117812 1970-01-05 NA 4 9 0.4874291 0.3898432 1970-01-06 NA 5 10 0.7383247 -0.6212406 1970-01-07 NA NA NA 0.5757814 -2.2146999 1970-01-08 NA NA NA -0.3053884 1.1249309 2003-02-01 -0.6264538 NA NA NA NA 2003-02-03 0.1836433 NA NA NA NA 2003-02-07 -0.8356286 NA NA NA NA 2003-02-09 1.5952808 NA NA NA NA 2003-02-14 0.3295078 NA NA NA NA > > ## extend an irregular series to a regular one: > # create a constant series > z <- zoo(1, seq(4)[-2]) > # create a 0 dimensional zoo series > z0 <- zoo(, 1:4) > # do the extension > merge(z, z0) 1 2 3 4 1 NA 1 1 > # same but with zero fill > merge(z, z0, fill = 0) 1 2 3 4 1 0 1 1 > > merge(z, coredata(z), 1) z coredata(z) 1 1 1 1 1 3 1 1 1 4 1 1 1 > > > ## merge multiple series represented in a long form data frame > ## into a multivariate zoo series and plot, one series for each site. > ## Additional examples can be found here: > ## https://stat.ethz.ch/pipermail/r-help/2009-February/187094.html > ## https://stat.ethz.ch/pipermail/r-help/2009-February/187096.html > ## > m <- 5 # no of years > n <- 6 # no of sites > sites <- LETTERS[1:n] > set.seed(1) > DF <- data.frame(site = sites, year = 2000 + 1:m, data = rnorm(m*n)) > tozoo <- function(x) zoo(x$data, x$year) > Data <- do.call(merge, lapply(split(DF, DF$site), tozoo)) > plot(Data, screen = 1, col = 1:n, pch = 1:n, type = "o", xlab = "") > legend("bottomleft", legend = sites, lty = 1, pch = 1:n, col = 1:n) > > ## for each index value in x merge it with the closest index value in y > ## but retaining x's times. > x<-zoo(1:3,as.Date(c("1992-12-13", "1997-05-12", "1997-07-13"))) > y<-zoo(1:5,as.Date(c("1992-12-15", "1992-12-16", "1997-05-10","1997-05-19", "1997-07-13"))) > f <- function(u) which.min(abs(as.numeric(index(y)) - as.numeric(u))) > ix <- sapply(index(x), f) > cbind(x, y = coredata(y)[ix]) x y 1992-12-13 1 1 1997-05-12 2 3 1997-07-13 3 5 > > ## this merges each element of x with the closest time point in y at or > ## after x's time point (whereas in previous example it could be before > ## or after) > window(na.locf(merge(x, y), fromLast = TRUE), index(x)) x y 1992-12-13 1 1 1997-05-12 2 4 1997-07-13 3 5 > > > > > > cleanEx() > nameEx("na.StructTS") > ### * na.StructTS > > flush(stderr()); flush(stdout()) > > ### Name: na.StructTS > ### Title: Fill NA or specified positions. > ### Aliases: na.StructTS na.StructTS.zoo na.StructTS.ts > ### Keywords: ts > > ### ** Examples > > > z <- zooreg(rep(10 * seq(4), each = 4) + rep(c(3, 1, 2, 4), times = 4), + start = as.yearqtr(2000), freq = 4) > z[10] <- NA > > zout <- na.StructTS(z) [1] "entering zoo method" [1] "entering ts method" > > plot(cbind(z, zout), screen = 1, col = 1:2, type = c("l", "p"), pch = 20) > > > > > > cleanEx() > nameEx("na.aggregate") > ### * na.aggregate > > flush(stderr()); flush(stdout()) > > ### Name: na.aggregate > ### Title: Replace NA by Aggregation > ### Aliases: na.aggregate na.aggregate.default > ### Keywords: ts > > ### ** Examples > > z <- zoo(c(1, NA, 3:9), + c(as.Date("2010-01-01") + 0:2, + as.Date("2010-02-01") + 0:2, + as.Date("2011-01-01") + 0:2)) > ## overall mean > na.aggregate(z) 2010-01-01 2010-01-02 2010-01-03 2010-02-01 2010-02-02 2010-02-03 2011-01-01 1.000 5.375 3.000 4.000 5.000 6.000 7.000 2011-01-02 2011-01-03 8.000 9.000 > ## group by months > na.aggregate(z, as.yearmon) 2010-01-01 2010-01-02 2010-01-03 2010-02-01 2010-02-02 2010-02-03 2011-01-01 1 2 3 4 5 6 7 2011-01-02 2011-01-03 8 9 > ## group by calendar months > na.aggregate(z, months) 2010-01-01 2010-01-02 2010-01-03 2010-02-01 2010-02-02 2010-02-03 2011-01-01 1.0 5.6 3.0 4.0 5.0 6.0 7.0 2011-01-02 2011-01-03 8.0 9.0 > ## group by years > na.aggregate(z, format, "%Y") 2010-01-01 2010-01-02 2010-01-03 2010-02-01 2010-02-02 2010-02-03 2011-01-01 1.0 3.8 3.0 4.0 5.0 6.0 7.0 2011-01-02 2011-01-03 8.0 9.0 > > > > cleanEx() > nameEx("na.approx") > ### * na.approx > > flush(stderr()); flush(stdout()) > > ### Name: na.approx > ### Title: Replace NA by Interpolation > ### Aliases: na.approx na.approx.zoo na.approx.zooreg na.approx.ts > ### na.approx.default na.spline na.spline.zoo na.spline.zooreg > ### na.spline.ts na.spline.default > ### Keywords: ts > > ### ** Examples > > > z <- zoo(c(2, NA, 1, 4, 5, 2), c(1, 3, 4, 6, 7, 8)) > > ## use underlying time scale for interpolation > na.approx(z) 1 3 4 6 7 8 2.000000 1.333333 1.000000 4.000000 5.000000 2.000000 > ## use equidistant spacing > na.approx(z, 1:6) 1 3 4 6 7 8 2.0 1.5 1.0 4.0 5.0 2.0 > > # with and without na.rm = FALSE > zz <- c(NA, 9, 3, NA, 3, 2) > na.approx(zz, na.rm = FALSE) [1] NA 9 3 3 3 2 > na.approx(zz) [1] 9 3 3 3 2 > > d0 <- as.Date("2000-01-01") > z <- zoo(c(11, NA, 13, NA, 15, NA), d0 + 1:6) > > # NA fill, drop or keep leading/trailing NAs > na.approx(z) 2000-01-02 2000-01-03 2000-01-04 2000-01-05 2000-01-06 11 12 13 14 15 > na.approx(z, na.rm = FALSE) 2000-01-02 2000-01-03 2000-01-04 2000-01-05 2000-01-06 2000-01-07 11 12 13 14 15 NA > > # extrapolate to point outside of range of time points > # (a) drop NA, (b) keep NA, (c) extrapolate using rule = 2 from approx() > na.approx(z, xout = d0 + 7) Data: numeric(0) Index: character(0) > na.approx(z, xout = d0 + 7, na.rm = FALSE) 2000-01-08 NA > na.approx(z, xout = d0 + 7, rule = 2) 2000-01-08 15 > > # use splines - extrapolation handled differently > z <- zoo(c(11, NA, 13, NA, 15, NA), d0 + 1:6) > na.spline(z) 2000-01-02 2000-01-03 2000-01-04 2000-01-05 2000-01-06 2000-01-07 11 12 13 14 15 16 > na.spline(z, na.rm = FALSE) 2000-01-02 2000-01-03 2000-01-04 2000-01-05 2000-01-06 2000-01-07 11 12 13 14 15 16 > na.spline(z, xout = d0 + 1:6) 2000-01-02 2000-01-03 2000-01-04 2000-01-05 2000-01-06 2000-01-07 11 12 13 14 15 16 > na.spline(z, xout = d0 + 2:5) 2000-01-03 2000-01-04 2000-01-05 2000-01-06 12 13 14 15 > na.spline(z, xout = d0 + 7) 2000-01-08 17 > na.spline(z, xout = d0 + 7, na.rm = FALSE) 2000-01-08 17 > > ## using na.approx for disaggregation > zy <- zoo(1:3, 2000:2001) > > # yearly to monthly series > zmo <- na.approx(zy, xout = as.yearmon(2000+0:13/12)) > zmo Jan 2000 Feb 2000 Mar 2000 Apr 2000 May 2000 Jun 2000 Jul 2000 Aug 2000 1.000000 1.083333 1.166667 1.250000 1.333333 1.416667 1.500000 1.583333 Sep 2000 Oct 2000 Nov 2000 Dec 2000 Jan 2001 1.666667 1.750000 1.833333 1.916667 2.000000 > > # monthly to daily series > sq <- seq(as.Date(start(zmo)), as.Date(end(zmo), frac = 1), by = "day") > zd <- na.approx(zmo, x = as.Date, xout = sq) > head(zd) 2000-01-01 2000-01-02 2000-01-03 2000-01-04 2000-01-05 2000-01-06 1.000000 1.002688 1.005376 1.008065 1.010753 1.013441 > > # weekly to daily series > zww <- zoo(1:3, as.Date("2001-01-01") + seq(0, length = 3, by = 7)) > zww 2001-01-01 2001-01-08 2001-01-15 1 2 3 > zdd <- na.approx(zww, xout = seq(start(zww), end(zww), by = "day")) > zdd 2001-01-01 2001-01-02 2001-01-03 2001-01-04 2001-01-05 2001-01-06 2001-01-07 1.000000 1.142857 1.285714 1.428571 1.571429 1.714286 1.857143 2001-01-08 2001-01-09 2001-01-10 2001-01-11 2001-01-12 2001-01-13 2001-01-14 2.000000 2.142857 2.285714 2.428571 2.571429 2.714286 2.857143 2001-01-15 3.000000 > > # The lines do not show up because of the NAs > plot(cbind(z, z), type = "b", screen = 1) > # use na.approx to force lines to appear > plot(cbind(z, na.approx(z)), type = "b", screen = 1) > > # Workaround where less than 2 NAs can appear in a column > za <- zoo(cbind(1:5, NA, c(1:3, NA, 5), NA)); za 1 1 NA 1 NA 2 2 NA 2 NA 3 3 NA 3 NA 4 4 NA NA NA 5 5 NA 5 NA > > ix <- colSums(!is.na(za)) > 0 > za[, ix] <- na.approx(za[, ix]); za 1 1 NA 1 NA 2 2 NA 2 NA 3 3 NA 3 NA 4 4 NA 4 NA 5 5 NA 5 NA > > # using na.approx to create regularly spaced series > # z has points at 10, 20 and 40 minutes while output also has a point at 30 > if(require("chron")) { + tt <- as.chron("2000-01-01 10:00:00") + c(1, 2, 4) * as.numeric(times("00:10:00")) + z <- zoo(1:3, tt) + tseq <- seq(start(z), end(z), by = times("00:10:00")) + na.approx(z, xout = tseq) + } Loading required package: chron (01/01/00 10:10:00) (01/01/00 10:20:00) (01/01/00 10:30:00) 1.0 2.0 2.5 > > > > cleanEx() detaching 'package:chron' > nameEx("na.fill") > ### * na.fill > > flush(stderr()); flush(stdout()) > > ### Name: na.fill > ### Title: Fill NA or specified positions. > ### Aliases: na.fill na.fill.ts na.fill.zoo na.fill.default > ### Keywords: ts > > ### ** Examples > > > z <- zoo(c(NA, 2, NA, 1, 4, 5, 2, NA)) > na.fill(z, "extend") 1 2 3 4 5 6 7 8 2.0 2.0 1.5 1.0 4.0 5.0 2.0 2.0 > na.fill(z, c("extend", NA)) 1 2 3 4 5 6 7 8 2 2 NA 1 4 5 2 2 > na.fill(z, -(1:3)) 1 2 3 4 5 6 7 8 -1 2 -2 1 4 5 2 -3 > na.fill(z, list(NA, NULL, NA)) 1 2 4 5 6 7 8 NA 2 1 4 5 2 NA > > > > > cleanEx() > nameEx("na.locf") > ### * na.locf > > flush(stderr()); flush(stdout()) > > ### Name: na.locf > ### Title: Last Observation Carried Forward > ### Aliases: na.locf na.locf.data.frame na.locf.list na.locf.default > ### Keywords: ts > > ### ** Examples > > az <- zoo(1:6) > > bz <- zoo(c(2,NA,1,4,5,2)) > na.locf(bz) 1 2 3 4 5 6 2 2 1 4 5 2 > na.locf(bz, fromLast = TRUE) 1 2 3 4 5 6 2 1 1 4 5 2 > > cz <- zoo(c(NA,9,3,2,3,2)) > na.locf(cz) 2 3 4 5 6 9 3 2 3 2 > > # generate and fill in missing dates > z <- zoo(c(0.007306621, 0.007659046, 0.007681013, + 0.007817548, 0.007847579, 0.007867313), + as.Date(c("1993-01-01", "1993-01-09", "1993-01-16", + "1993-01-23", "1993-01-30", "1993-02-06"))) > g <- seq(start(z), end(z), "day") > na.locf(z, xout = g) 1993-01-01 1993-01-02 1993-01-03 1993-01-04 1993-01-05 1993-01-06 0.007306621 0.007306621 0.007306621 0.007306621 0.007306621 0.007306621 1993-01-07 1993-01-08 1993-01-09 1993-01-10 1993-01-11 1993-01-12 0.007306621 0.007306621 0.007659046 0.007659046 0.007659046 0.007659046 1993-01-13 1993-01-14 1993-01-15 1993-01-16 1993-01-17 1993-01-18 0.007659046 0.007659046 0.007659046 0.007681013 0.007681013 0.007681013 1993-01-19 1993-01-20 1993-01-21 1993-01-22 1993-01-23 1993-01-24 0.007681013 0.007681013 0.007681013 0.007681013 0.007817548 0.007817548 1993-01-25 1993-01-26 1993-01-27 1993-01-28 1993-01-29 1993-01-30 0.007817548 0.007817548 0.007817548 0.007817548 0.007817548 0.007847579 1993-01-31 1993-02-01 1993-02-02 1993-02-03 1993-02-04 1993-02-05 0.007847579 0.007847579 0.007847579 0.007847579 0.007847579 0.007847579 1993-02-06 0.007867313 > > # similar but use a 2 second grid > > z <- zoo(1:9, as.POSIXct(c("2010-01-04 09:30:02", "2010-01-04 09:30:06", + "2010-01-04 09:30:07", "2010-01-04 09:30:08", "2010-01-04 09:30:09", + "2010-01-04 09:30:10", "2010-01-04 09:30:11", "2010-01-04 09:30:13", + "2010-01-04 09:30:14"))) > > g <- seq(start(z), end(z), by = "2 sec") > na.locf(z, xout = g) 2010-01-04 09:30:02 2010-01-04 09:30:04 2010-01-04 09:30:06 2010-01-04 09:30:08 1 1 2 4 2010-01-04 09:30:10 2010-01-04 09:30:12 2010-01-04 09:30:14 6 7 9 > > ## get 5th of every month or most recent date prior to 5th if 5th missing. > ## Result has index of the date actually used. > > z <- zoo(c(1311.56, 1309.04, 1295.5, 1296.6, 1286.57, 1288.12, + 1289.12, 1289.12, 1285.33, 1307.65, 1309.93, 1311.46, 1311.28, + 1308.11, 1301.74, 1305.41, 1309.72, 1310.61, 1305.19, 1313.21, + 1307.85, 1312.25, 1325.76), as.Date(c(13242, 13244, + 13245, 13248, 13249, 13250, 13251, 13252, 13255, 13256, 13257, + 13258, 13259, 13262, 13263, 13264, 13265, 13266, 13269, 13270, + 13271, 13272, 13274))) > > # z.na is same as z but with missing days added (with NAs) > # It is formed by merging z with a zero with series having all the dates. > > rng <- range(time(z)) > z.na <- merge(z, zoo(, seq(rng[1], rng[2], by = "day"))) > > # use na.locf to bring values forward picking off 5th of month > na.locf(z.na)[as.POSIXlt(time(z.na))$mday == 5] 2006-04-05 2006-05-05 1311.56 1312.25 > > ## this is the same as the last one except instead of always using the > ## 5th of month in the result we show the date actually used > > # idx has NAs wherever z.na does but has 1, 2, 3, ... instead of > # z.na's data values (so idx can be used for indexing) > > idx <- coredata(na.locf(seq_along(z.na) + (0 * z.na))) > > # pick off those elements of z.na that correspond to 5th > > z.na[idx[as.POSIXlt(time(z.na))$mday == 5]] 2006-04-04 2006-05-04 1311.56 1312.25 > > ## only fill single-day gaps > > merge(z.na, filled1 = na.locf(z.na, maxgap = 1)) z.na filled1 2006-04-04 1311.56 1311.56 2006-04-05 NA 1311.56 2006-04-06 1309.04 1309.04 2006-04-07 1295.50 1295.50 2006-04-08 NA NA 2006-04-09 NA NA 2006-04-10 1296.60 1296.60 2006-04-11 1286.57 1286.57 2006-04-12 1288.12 1288.12 2006-04-13 1289.12 1289.12 2006-04-14 1289.12 1289.12 2006-04-15 NA NA 2006-04-16 NA NA 2006-04-17 1285.33 1285.33 2006-04-18 1307.65 1307.65 2006-04-19 1309.93 1309.93 2006-04-20 1311.46 1311.46 2006-04-21 1311.28 1311.28 2006-04-22 NA NA 2006-04-23 NA NA 2006-04-24 1308.11 1308.11 2006-04-25 1301.74 1301.74 2006-04-26 1305.41 1305.41 2006-04-27 1309.72 1309.72 2006-04-28 1310.61 1310.61 2006-04-29 NA NA 2006-04-30 NA NA 2006-05-01 1305.19 1305.19 2006-05-02 1313.21 1313.21 2006-05-03 1307.85 1307.85 2006-05-04 1312.25 1312.25 2006-05-05 NA 1312.25 2006-05-06 1325.76 1325.76 > > ## fill NAs in first column by inflating the most recent non-NA > ## by the growth in second column. Note that elements of x-x > ## are NA if the corresponding element of x is NA and zero else > > m <- zoo(cbind(c(1, 2, NA, NA, 5, NA, NA), seq(7)^2), as.Date(1:7)) > > r <- na.locf(m[,1]) * m[,2] / na.locf(m[,2] + (m[,1]-m[,1])) > cbind(V1 = r, V2 = m[,2]) V1 V2 1970-01-02 1.0 1 1970-01-03 2.0 4 1970-01-04 4.5 9 1970-01-05 8.0 16 1970-01-06 5.0 25 1970-01-07 7.2 36 1970-01-08 9.8 49 > > ## repeat a quarterly value every month > ## preserving NAs > zq <- zoo(c(1, NA, 3, 4), as.yearqtr(2000) + 0:3/4) > tt <- as.yearmon(start(zq)) + seq(0, len = 3 * length(zq))/12 > na.locf(zq, xout = tt, maxgap = 0) Jan 2000 Feb 2000 Mar 2000 Apr 2000 May 2000 Jun 2000 Jul 2000 Aug 2000 1 1 1 NA NA NA 3 3 Sep 2000 Oct 2000 Nov 2000 Dec 2000 3 4 4 4 > > > > > > cleanEx() > nameEx("na.trim") > ### * na.trim > > flush(stderr()); flush(stdout()) > > ### Name: na.trim > ### Title: Trim Leading/Trailing Missing Observations > ### Aliases: na.trim na.trim.default na.trim.ts > ### Keywords: ts > > ### ** Examples > > # examples of na.trim > x <- zoo(c(1, 4, 6), c(2, 4, 6)) > xx <- zoo(matrix(c(1, 4, 6, NA, 5, 7), 3), c(2, 4, 6)) > na.trim(x) 2 4 6 1 4 6 > na.trim(xx) 4 4 5 6 6 7 > > # using na.trim for alignment > # cal defines the legal dates > # all dates within the date range of x should be present > cal <- zoo(,c(1, 2, 3, 6, 7)) > x <- zoo(c(12, 16), c(2, 6)) > na.trim(merge(x, cal)) 2 3 6 12 NA 16 > > > > > cleanEx() > nameEx("plot.zoo") > ### * plot.zoo > > flush(stderr()); flush(stdout()) > > ### Name: plot.zoo > ### Title: Plotting zoo Objects > ### Aliases: plot.zoo barplot.zoo lines.zoo points.zoo > ### Keywords: ts > > ### ** Examples > > ## example dates > x.Date <- as.Date(paste(2003, 02, c(1, 3, 7, 9, 14), sep = "-")) > > ## univariate plotting > x <- zoo(rnorm(5), x.Date) > x2 <- zoo(rnorm(5, sd = 0.2), x.Date) > plot(x) > lines(x2, col = 2) > > ## multivariate plotting > z <- cbind(x, x2, zoo(rnorm(5, sd = 0.5), x.Date)) > plot(z, type = "b", pch = 1:3, col = 1:3, ylab = list(expression(mu), "b", "c")) > colnames(z) <- LETTERS[1:3] > plot(z, screens = 1, col = list(B = 2)) > plot(z, type = "b", pch = 1:3, col = 1:3) > plot(z, type = "b", pch = list(A = 1:5, B = 3), col = list(C = 4, 2)) > plot(z, type = "b", screen = c(1,2,1), col = 1:3) > # right axis is for broken lines > plot(x) > opar <- par(usr = c(par("usr")[1:2], range(x2))) > lines(x2, lty = 2) > # axis(4) > axis(side = 4) > par(opar) > > > ## Custom x axis labelling using a custom panel. > # 1. test data > z <- zoo(c(21, 34, 33, 41, 39, 38, 37, 28, 33, 40), + as.Date(c("1992-01-10", "1992-01-17", "1992-01-24", "1992-01-31", + "1992-02-07", "1992-02-14", "1992-02-21", "1992-02-28", "1992-03-06", + "1992-03-13"))) > zz <- merge(a = z, b = z+10) > # 2. axis tick for every point. Also every 3rd point labelled. > my.panel <- function(x, y, ..., pf = parent.frame()) { + fmt <- "%b-%d" # format for axis labels + lines(x, y, ...) + # if bottom panel + if (with(pf, length(panel.number) == 0 || + panel.number %% nr == 0 || panel.number == nser)) { + # create ticks at x values and then label every third tick + axis(side = 1, at = x, labels = FALSE) + ix <- seq(1, length(x), 3) + labs <- format(x, fmt) + axis(side = 1, at = x[ix], labels = labs[ix], tcl = -0.7, cex.axis = 0.7) + } + } > # 3. plot > plot(zz, panel = my.panel, xaxt = "n") > > # with a single panel plot a fancy x-axis is just the same > # procedure as for the ordinary plot command > plot(zz, screen = 1, col = 1:2, xaxt = "n") > # axis(1, at = time(zz), labels = FALSE) > tt <- time(zz) > axis(side = 1, at = tt, labels = FALSE) > ix <- seq(1, length(tt), 3) > fmt <- "%b-%d" # format for axis labels > labs <- format(tt, fmt) > # axis(1, at = time(zz)[ix], labels = labs[ix], tcl = -0.7, cex.axis = 0.7) > axis(side = 1, at = tt[ix], labels = labs[ix], tcl = -0.7, cex.axis = 0.7) > legend("bottomright", colnames(zz), lty = 1, col = 1:2) > > ## plot a mulitple ts series with nice x-axis using panel function > tab <- ts(cbind(A = 1:24, B = 24:1), start = c(2006, 1), freq = 12) > pnl.xaxis <- function(...) { + lines(...) + panel.number <- parent.frame()$panel.number + nser <- parent.frame()$nser + # if bottom panel + if (!length(panel.number) || panel.number == nser) { + tt <- list(...)[[1]] + ym <- as.yearmon(tt) + mon <- as.numeric(format(ym, "%m")) + yy <- format(ym, "%y") + mm <- substring(month.abb[mon], 1, 1) + if (any(mon == 1)) + # axis(1, tt[mon == 1], yy[mon == 1], cex.axis = 0.7) + axis(side = 1, at = tt[mon == 1], labels = yy[mon == 1], cex.axis = 0.7) + # axis(1, tt[mon > 1], mm[mon > 1], cex.axis = 0.5, tcl = -0.3) + axis(side = 1, at = tt[mon > 1], labels = mm[mon > 1], cex.axis = 0.5, tcl = -0.3) + } + } > plot(as.zoo(tab), panel = pnl.xaxis, xaxt = "n", main = "Fancy X Axis") > > ## Another example with a custom axis > # test data > z <- zoo(matrix(1:25, 5), c(10,11,20,21)) > colnames(z) <- letters[1:5] > > plot(zoo(coredata(z)), xaxt = "n", panel = function(x, y, ..., Time = time(z)) { + lines(x, y, ...) + # if bottom panel + pf <- parent.frame() + if (with(pf, panel.number %% nr == 0 || panel.number == nser)) { + axis(side = 1, at = x, labels = Time) + } + }) > > > ## plot with left and right axes > ## modified from http://www.mayin.org/ajayshah/KB/R/html/g6.html > set.seed(1) > z <- zoo(cbind(A = cumsum(rnorm(100)), B = cumsum(rnorm(100, mean = 0.2)))) > opar <- par(mai = c(.8, .8, .2, .8)) > plot(z[,1], type = "l", + xlab = "x-axis label", ylab = colnames(z)[1]) > par(new = TRUE) > plot(z[,2], type = "l", ann = FALSE, yaxt = "n", col = "blue") > # axis(4) > axis(side = 4) > legend(x = "topleft", bty = "n", lty = c(1,1), col = c("black", "blue"), + legend = paste(colnames(z), c("(left scale)", "(right scale)"))) > usr <- par("usr") > # if you don't care about srt= in text then mtext is shorter: > # mtext(colnames(z)[2], 4, 2, col = "blue") > text(usr[2] + .1 * diff(usr[1:2]), mean(usr[3:4]), colnames(z)[2], + srt = -90, xpd = TRUE, col = "blue") > par(opar) > > # automatically placed point labels > ## Not run: > ##D library("maptools") > ##D pointLabel(time(z), coredata(z[,2]), labels = format(time(z)), cex = 0.5) > ## End(Not run) > > ## plot one zoo series against the other. > plot(x, x2) > plot(x, x2, xy.labels = TRUE) > plot(x, x2, xy.labels = 1:5, xy.lines = FALSE) > > ## shade a portion of a plot and make axis fancier > > v <- zooreg(rnorm(50), start = as.yearmon(2004), freq = 12) > > plot(v, type = "n") > u <- par("usr") > rect(as.yearmon("2007-8"), u[3], as.yearmon("2009-11"), u[4], + border = 0, col = "grey") > lines(v) > axis(1, floor(time(v)), labels = FALSE, tcl = -1) > > ## shade certain times to show recessions, etc. > v <- zooreg(rnorm(50), start = as.yearmon(2004), freq = 12) > plot(v, type = "n") > u <- par("usr") > rect(as.yearmon("2007-8"), u[3], as.yearmon("2009-11"), u[4], + border = 0, col = "grey") > lines(v) > axis(1, floor(time(v)), labels = FALSE, tcl = -1) > > ## fill area under plot > > pnl.xyarea <- function(x, y, fill.base = 0, col = 1, ...) { + lines(x, y, ...) + panel.number <- parent.frame()$panel.number + col <- rep(col, length = panel.number)[panel.number] + polygon(c(x[1], x, tail(x, 1), x[1]), + c(fill.base, as.numeric(y), fill.base, fill.base), col = col) + } > plot(zoo(EuStockMarkets), col = rainbow(4), panel = pnl.xyarea) > > > ## barplot > x <- zoo(cbind(rpois(5, 2), rpois(5, 3)), x.Date) > barplot(x, beside = TRUE) > > ## 3d plot > ## The persp function in R (not part of zoo) works with zoo objects. > ## The following example is by Enrico Schumann. > ## https://stat.ethz.ch/pipermail/r-sig-finance/2009q1/003710.html > nC <- 10 # columns > nO <- 100 # observations > dataM <- array(runif(nC * nO), dim=c(nO, nC)) > zz <- zoo(dataM, 1:nO) > persp(1:nO, 1:nC, zz) > > # interactive plotting > ## Not run: > ##D library("TeachingDemos") > ##D tke.test1 <- list(Parameters = list( > ##D lwd = list("spinbox", init = 1, from = 0, to = 5, increment = 1, width = 5), > ##D lty = list("spinbox", init = 1, from = 0, to = 6, increment = 1, width = 5) > ##D )) > ##D z <- zoo(rnorm(25)) > ##D tkexamp(plot(z), tke.test1, plotloc = "top") > ## End(Not run) > > > > > graphics::par(get("par.postscript", pos = 'CheckExEnv')) > cleanEx() > nameEx("read.zoo") > ### * read.zoo > > flush(stderr()); flush(stdout()) > > ### Name: read.zoo > ### Title: Reading and Writing zoo Series > ### Aliases: read.zoo write.zoo > ### Keywords: ts > > ### ** Examples > > ## Not run: > ##D ## turn *numeric* first column into yearmon index > ##D ## where number is year + fraction of year represented by month > ##D z <- read.zoo("foo.csv", sep = ",", FUN = as.yearmon) > ##D > ##D ## first column is of form yyyy.mm > ##D ## (Here we use format in place of as.character so that final zero > ##D ## is not dropped in dates like 2001.10 which as.character would do.) > ##D f <- function(x) as.yearmon(format(x, nsmall = 2), "%Y.%m") > ##D z <- read.zoo("foo.csv", header = TRUE, FUN = f) > ##D > ##D ## turn *character* first column into "Date" index > ##D ## Assume lines look like: 12/22/2007 1 2 > ##D z <- read.zoo("foo.tab", format = "%m/%d/%Y") > ##D > ##D # Suppose lines look like: 09112007 1 2 and there is no header > ##D z <- read.zoo("foo.txt", format = "%d%m%Y") > ##D > ##D ## csv file with first column of form YYYY-mm-dd HH:MM:SS > ##D ## Read in times as "chron" class. Requires chron 2.3-22 or later. > ##D z <- read.zoo("foo.csv", header = TRUE, sep = ",", FUN = as.chron) > ##D > ##D ## same but with custom format. Note as.chron uses POSIXt-style ##D > ##D ## Read in times as "chron" class. Requires chron 2.3-24 or later. > ##D z <- read.zoo("foo.csv", header = TRUE, sep = ",", FUN = as.chron, > ##D format = "##D > ##D > ##D ## same file format but read it in times as "POSIXct" class. > ##D z <- read.zoo("foo.csv", header = TRUE, sep = ",", tz = "") > ##D > ##D ## csv file with first column mm-dd-yyyy. Read times as "Date" class. > ##D z <- read.zoo("foo.csv", header = TRUE, sep = ",", format = "%m-%d-%Y") > ##D > ##D ## whitespace separated file with first column of form YYYY-mm-ddTHH:MM:SS > ##D ## and no headers. T appears literally. Requires chron 2.3-22 or later. > ##D z <- read.zoo("foo.csv", FUN = as.chron) > ##D > ##D # We use "NULL" in colClasses for those columns we don't need but in > ##D # col.names we still have to include dummy names for them. Of what > ##D # is left the index is the first three columns (1:3) which we convert > ##D # to chron class times in FUN and then truncate to 5 seconds in FUN2. > ##D # Finally we use aggregate = mean to average over the 5 second intervals. > ##D library("chron") > ##D > ##D Lines <- "CVX 20070201 9 30 51 73.25 81400 0 > ##D CVX 20070201 9 30 51 73.25 100 0 > ##D CVX 20070201 9 30 51 73.25 100 0 > ##D CVX 20070201 9 30 51 73.25 300 0 > ##D CVX 20070201 9 30 51 73.25 81400 0 > ##D CVX 20070201 9 40 51 73.25 100 0 > ##D CVX 20070201 9 40 52 73.25 100 0 > ##D CVX 20070201 9 40 53 73.25 300 0" > ##D > ##D z <- read.zoo(textConnection(Lines), > ##D colClasses = c("NULL", "NULL", "numeric", "numeric", "numeric", "numeric", > ##D "numeric", "NULL"), > ##D col.names = c("Symbol", "Date", "Hour", "Minute", "Second", "Price", > ##D "Volume", "junk"), > ##D index = 1:3, # do not count columns that are "NULL" in colClasses > ##D FUN = function(h, m, s) times(paste(h, m, s, sep = ":")), > ##D FUN2 = function(tt) trunc(tt, "00:00:05"), > ##D aggregate = mean) > ##D > ##D ## omit the read.table() phase and directly supply a data.frame > ##D dat <- data.frame(date = paste("2000-01-", 10:15, sep = ""), a = rnorm(6), b = 1:6) > ##D z <- read.zoo(dat) > ##D > ##D ## using built-in data frame BOD > ##D read.zoo(BOD) > ##D > ##D read.zoo(BOD, FUN = as.Date) > ##D > ##D read.zoo(BOD[c(1:6, 1), ], aggregate = mean) > ##D > ##D \dontrun{ > ##D # read in all csv files in the current directory and merge them > ##D read.zoo(Sys.glob("*.csv"), header = TRUE, sep = ",") > ##D } > ##D > ## End(Not run) > > > > cleanEx() > nameEx("rollapply") > ### * rollapply > > flush(stderr()); flush(stdout()) > > ### Name: rollapply > ### Title: Apply Rolling Functions > ### Aliases: rollapply rollapplyr rollapply.default rollapply.ts > ### rollapply.zoo > ### Keywords: iteration array ts > > ### ** Examples > > ## rolling mean > z <- zoo(11:15, as.Date(31:35)) > rollapply(z, 2, mean) 1970-02-01 1970-02-02 1970-02-03 1970-02-04 11.5 12.5 13.5 14.5 > > ## non-overlapping means > z2 <- zoo(rnorm(6)) > rollapply(z2, 3, mean, by = 3) # means of nonoverlapping groups of 3 2 5 -0.4261464 0.3681067 > aggregate(z2, c(3,3,3,6,6,6), mean) # same 3 6 -0.4261464 0.3681067 > > ## optimized vs. customized versions > rollapply(z2, 3, mean) # uses rollmean which is optimized for mean 2 3 4 5 -0.4261464 0.3144318 0.3630533 0.3681067 > rollmean(z2, 3) # same 2 3 4 5 -0.4261464 0.3144318 0.3630533 0.3681067 > rollapply(z2, 3, (mean)) # does not use rollmean 2 3 4 5 -0.4261464 0.3144318 0.3630533 0.3681067 > > ## rolling regression: > ## set up multivariate zoo series with > ## number of UK driver deaths and lags 1 and 12 > seat <- as.zoo(log(UKDriverDeaths)) > time(seat) <- as.yearmon(time(seat)) > seat <- merge(y = seat, y1 = lag(seat, k = -1), + y12 = lag(seat, k = -12), all = FALSE) > > ## run a rolling regression with a 3-year time window > ## (similar to a SARIMA(1,0,0)(1,0,0)_12 fitted by OLS) > rr <- rollapply(seat, width = 36, + FUN = function(z) coef(lm(y ~ y1 + y12, data = as.data.frame(z))), + by.column = FALSE, align = "right") > > ## plot the changes in coefficients > ## showing the shifts after the oil crisis in Oct 1973 > ## and after the seatbelt legislation change in Jan 1983 > plot(rr) > > ## different values of rule argument > z <- zoo(c(NA, NA, 2, 3, 4, 5, NA)) > rollapply(z, 3, sum, na.rm = TRUE) 2 3 4 5 6 2 5 9 12 9 > rollapply(z, 3, sum, na.rm = TRUE, fill = NULL) 2 3 4 5 6 2 5 9 12 9 > rollapply(z, 3, sum, na.rm = TRUE, fill = NA) 1 2 3 4 5 6 7 NA 2 5 9 12 9 NA > rollapply(z, 3, sum, na.rm = TRUE, partial = TRUE) 1 2 3 4 5 6 7 0 2 5 9 12 9 5 > > # this will exclude time points 1 and 2 > # It corresonds to align = "right", width = 3 > rollapply(zoo(1:8), list(seq(-2, 0)), sum) 3 4 5 6 7 8 6 9 12 15 18 21 > > # but this will include points 1 and 2 > rollapply(zoo(1:8), list(seq(-2, 0)), sum, partial = 1) 1 2 3 4 5 6 7 8 1 3 6 9 12 15 18 21 > rollapply(zoo(1:8), list(seq(-2, 0)), sum, partial = 0) 1 2 3 4 5 6 7 8 1 3 6 9 12 15 18 21 > > # so will this > rollapply(zoo(1:8), list(seq(-2, 0)), sum, fill = NA) 1 2 3 4 5 6 7 8 NA NA 6 9 12 15 18 21 > > # by = 3, align = "right" > L <- rep(list(NULL), 8) > L[seq(3, 8, 3)] <- list(seq(-2, 0)) > str(L) List of 8 $ : NULL $ : NULL $ : int [1:3] -2 -1 0 $ : NULL $ : NULL $ : int [1:3] -2 -1 0 $ : NULL $ : NULL > rollapply(zoo(1:8), L, sum) 3 6 6 15 > > rollapply(zoo(1:8), list(0:2), sum, fill = 1:3) 1 2 3 4 5 6 7 8 6 9 12 15 18 21 3 3 > rollapply(zoo(1:8), list(0:2), sum, fill = 3) 1 2 3 4 5 6 7 8 6 9 12 15 18 21 3 3 > > L2 <- rep(list(-(2:0)), 10) > L2[5] <- list(NULL) > str(L2) List of 10 $ : int [1:3] -2 -1 0 $ : int [1:3] -2 -1 0 $ : int [1:3] -2 -1 0 $ : int [1:3] -2 -1 0 $ : NULL $ : int [1:3] -2 -1 0 $ : int [1:3] -2 -1 0 $ : int [1:3] -2 -1 0 $ : int [1:3] -2 -1 0 $ : int [1:3] -2 -1 0 > rollapply(zoo(1:10), L2, sum, fill = "extend") 1 2 3 4 5 6 7 8 9 10 6 6 6 9 12 15 18 21 24 27 > rollapply(zoo(1:10), L2, sum, fill = list("extend", NULL)) 1 2 3 4 6 7 8 9 10 6 6 6 9 15 18 21 24 27 > > rollapply(zoo(1:10), L2, sum, fill = list("extend", NA)) 1 2 3 4 5 6 7 8 9 10 6 6 6 9 NA 15 18 21 24 27 > > rollapply(zoo(1:10), L2, sum, fill = NA) 1 2 3 4 5 6 7 8 9 10 NA NA 6 9 NA 15 18 21 24 27 > rollapply(zoo(1:10), L2, sum, fill = 1:3) 1 2 3 4 5 6 7 8 9 10 1 1 6 9 2 15 18 21 24 27 > rollapply(zoo(1:10), L2, sum, partial = TRUE) 1 2 3 4 6 7 8 9 10 1 3 6 9 15 18 21 24 27 > rollapply(zoo(1:10), L2, sum, partial = TRUE, fill = 99) 1 2 3 4 5 6 7 8 9 10 1 3 6 9 99 15 18 21 24 27 > > rollapply(zoo(1:10), list(-1), sum, partial = 0) 1 2 3 4 5 6 7 8 9 10 0 1 2 3 4 5 6 7 8 9 > rollapply(zoo(1:10), list(-1), sum, partial = TRUE) 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 > > rollapply(zoo(cbind(a = 1:6, b = 11:16)), 3, rowSums, by.column = FALSE) 2 12 14 16 3 14 16 18 4 16 18 20 5 18 20 22 > > # these two are the same > rollapply(zoo(cbind(a = 1:6, b = 11:16)), 3, sum) a b 2 6 36 3 9 39 4 12 42 5 15 45 > rollapply(zoo(cbind(a = 1:6, b = 11:16)), 3, colSums, by.column = FALSE) a b 2 6 36 3 9 39 4 12 42 5 15 45 > > # these two are the same > rollapply(zoo(1:6), 2, sum, by = 2, align = "right") 2 4 6 3 7 11 > aggregate(zoo(1:6), c(2, 2, 4, 4, 6, 6), sum) 2 4 6 3 7 11 > > # these two are the same > rollapply(zoo(1:3), list(-1), c) 2 3 1 2 > lag(zoo(1:3), -1) 2 3 1 2 > > # these two are the same > rollapply(zoo(1:3), list(1), c) 1 2 2 3 > lag(zoo(1:3)) 1 2 2 3 > > # these two are the same > rollapply(zoo(1:5), list(c(-1, 0, 1)), sum) 2 3 4 6 9 12 > rollapply(zoo(1:5), 3, sum) 2 3 4 6 9 12 > > # these two are the same > rollapply(zoo(1:5), list(0:2), sum) 1 2 3 6 9 12 > rollapply(zoo(1:5), 3, sum, align = "left") 1 2 3 6 9 12 > > # these two are the same > rollapply(zoo(1:5), list(-(2:0)), sum) 3 4 5 6 9 12 > rollapply(zoo(1:5), 3, sum, align = "right") 3 4 5 6 9 12 > > # these two are the same > rollapply(zoo(1:6), list(NULL, NULL, -(2:0)), sum) 3 6 6 15 > rollapply(zoo(1:6), 3, sum, by = 3, align = "right") 3 6 6 15 > > # these two are the same > rollapply(zoo(1:5), list(c(-1, 1)), sum) 2 3 4 4 6 8 > rollapply(zoo(1:5), 3, function(x) sum(x[-2])) 2 3 4 4 6 8 > > # these two are the same > rollapply(1:5, 3, rev) [,1] [,2] [,3] [1,] 3 2 1 [2,] 4 3 2 [3,] 5 4 3 > embed(1:5, 3) [,1] [,2] [,3] [1,] 3 2 1 [2,] 4 3 2 [3,] 5 4 3 > > # these four are the same > x <- 1:6 > rollapply(c(0, 0, x), 3, sum, align = "right") - x [1] 0 1 3 5 7 9 > rollapply(x, 3, sum, partial = TRUE, align = "right") - x [1] 0 1 3 5 7 9 > rollapply(x, 3, function(x) sum(x[-3]), partial = TRUE, align = "right") [1] 1 3 3 5 7 9 > rollapply(x, list(-(2:1)), sum, partial = 0) [1] 0 1 3 5 7 9 > > # same as Matlab's buffer(x, n, p) for valid non-negative p > # See http://www.mathworks.com/help/toolbox/signal/buffer.html > x <- 1:30; n <- 7; p <- 3 > t(rollapply(c(rep(0, p), x, rep(0, n-p)), n, by = n-p, c)) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [1,] 0 2 6 10 14 18 22 26 [2,] 0 3 7 11 15 19 23 27 [3,] 0 4 8 12 16 20 24 28 [4,] 1 5 9 13 17 21 25 29 [5,] 2 6 10 14 18 22 26 30 [6,] 3 7 11 15 19 23 27 0 [7,] 4 8 12 16 20 24 28 0 > > # these three are the same > y <- 10 * seq(8); k <- 4; d <- 2 > # 1 > # from http://ucfagls.wordpress.com/2011/06/14/embedding-a-time-series-with-time-delay-in-r-part-ii/ > Embed <- function(x, m, d = 1, indices = FALSE, as.embed = TRUE) { + n <- length(x) - (m-1)*d + X <- seq_along(x) + if(n <= 0) + stop("Insufficient observations for the requested embedding") + out <- matrix(rep(X[seq_len(n)], m), ncol = m) + out[,-1] <- out[,-1, drop = FALSE] + + rep(seq_len(m - 1) * d, each = nrow(out)) + if(as.embed) + out <- out[, rev(seq_len(ncol(out)))] + if(!indices) + out <- matrix(x[out], ncol = m) + out + } > Embed(y, k, d) [,1] [,2] [,3] [,4] [1,] 70 50 30 10 [2,] 80 60 40 20 > # 2 > rollapply(y, list(-d * seq(0, k-1)), c) [,1] [,2] [,3] [,4] [1,] 70 50 30 10 [2,] 80 60 40 20 > # 3 > rollapply(y, d*k-1, function(x) x[d * seq(k-1, 0) + 1]) [,1] [,2] [,3] [,4] [1,] 70 50 30 10 [2,] 80 60 40 20 > > > > > cleanEx() > nameEx("rollmean") > ### * rollmean > > flush(stderr()); flush(stdout()) > > ### Name: rollmean > ### Title: Rolling Means/Maximums/Medians > ### Aliases: rollmean rollsum rollmeanr rollsumr rollmax rollmaxr > ### rollmedian rollmedianr rollmean.zoo rollsum.zoo rollmedian.zoo > ### rollmax.zoo rollmean.ts rollsum.ts rollmedian.ts rollmax.ts > ### rollmean.default rollsum.default rollmedian.default rollmax.default > ### Keywords: ts > > ### ** Examples > > x.Date <- as.Date(paste(2004, rep(1:4, 4:1), sample(1:28, 10), sep = "-")) > x <- zoo(rnorm(12), x.Date) > > rollmean(x, 3) 2004-01-11 2004-01-15 2004-01-23 2004-02-05 2004-02-21 2004-02-25 2004-03-13 0.1350951 0.6005117 0.3362392 0.5940580 0.5320787 -0.1043585 -0.8153657 2004-03-14 -0.5703365 > rollmax(x, 3) 2004-01-11 2004-01-15 2004-01-23 2004-02-05 2004-02-21 2004-02-25 2004-03-13 0.7383247 0.7383247 0.7383247 1.5117812 1.5117812 1.5117812 0.3898432 2004-03-14 1.1249309 > rollmedian(x, 3) 2004-01-11 2004-01-15 2004-01-23 2004-02-05 2004-02-21 2004-02-25 2004-03-13 0.4874291 0.5757814 0.5757814 0.5757814 0.3898432 0.3898432 -0.6212406 2004-03-14 -0.6212406 > > xm <- zoo(matrix(1:12, 4, 3), x.Date[1:4]) > rollmean(xm, 3) 2004-01-11 2 6 10 2004-01-15 3 7 11 > rollmax(xm, 3) 2004-01-11 3 7 11 2004-01-15 4 8 12 > rollmedian(xm, 3) 2004-01-11 2 6 10 2004-01-15 3 7 11 > > rollapply(xm, 3, mean) # uses rollmean 2004-01-11 2 6 10 2004-01-15 3 7 11 > rollapply(xm, 3, function(x) mean(x)) # does not use rollmean 2004-01-11 2 6 10 2004-01-15 3 7 11 > > > > > cleanEx() > nameEx("window.zoo") > ### * window.zoo > > flush(stderr()); flush(stdout()) > > ### Name: window.zoo > ### Title: Extract/Replacing the Time Windows of Objects > ### Aliases: window.zoo window<-.zoo > ### Keywords: ts > > ### ** Examples > > ## zoo example > x.date <- as.Date(paste(2003, rep(1:4, 4:1), seq(1,19,2), sep = "-")) > x <- zoo(matrix(rnorm(20), ncol = 2), x.date) > x 2003-01-01 -0.6264538 1.51178117 2003-01-03 0.1836433 0.38984324 2003-01-05 -0.8356286 -0.62124058 2003-01-07 1.5952808 -2.21469989 2003-02-09 0.3295078 1.12493092 2003-02-11 -0.8204684 -0.04493361 2003-02-13 0.4874291 -0.01619026 2003-03-15 0.7383247 0.94383621 2003-03-17 0.5757814 0.82122120 2003-04-19 -0.3053884 0.59390132 > > window(x, start = as.Date("2003-02-01"), end = as.Date("2003-03-01")) 2003-02-09 0.3295078 1.12493092 2003-02-11 -0.8204684 -0.04493361 2003-02-13 0.4874291 -0.01619026 > window(x, index = x.date[1:6], start = as.Date("2003-02-01")) 2003-02-09 0.3295078 1.12493092 2003-02-11 -0.8204684 -0.04493361 > window(x, index = x.date[c(4, 8, 10)]) 2003-01-07 1.5952808 -2.2146999 2003-03-15 0.7383247 0.9438362 2003-04-19 -0.3053884 0.5939013 > window(x, index = x.date[c(4, 8, 10)]) <- matrix(1:6, ncol = 2) > x 2003-01-01 -0.6264538 1.51178117 2003-01-03 0.1836433 0.38984324 2003-01-05 -0.8356286 -0.62124058 2003-01-07 1.0000000 4.00000000 2003-02-09 0.3295078 1.12493092 2003-02-11 -0.8204684 -0.04493361 2003-02-13 0.4874291 -0.01619026 2003-03-15 2.0000000 5.00000000 2003-03-17 0.5757814 0.82122120 2003-04-19 3.0000000 6.00000000 > > ## for classes that support comparisons with "character" variables > ## start and end may be "character". > window(x, start = "2003-02-01") 2003-02-09 0.3295078 1.12493092 2003-02-11 -0.8204684 -0.04493361 2003-02-13 0.4874291 -0.01619026 2003-03-15 2.0000000 5.00000000 2003-03-17 0.5757814 0.82122120 2003-04-19 3.0000000 6.00000000 > > ## zooreg example (with plain numeric index) > z <- zooreg(rnorm(10), start = 2000, freq = 4) > window(z, start = 2001.75) 2001(4) 2002(1) 2002(2) -1.4707524 -0.4781501 0.4179416 > window(z, start = c(2001, 4)) 2001(4) 2002(1) 2002(2) -1.4707524 -0.4781501 0.4179416 > > ## replace data at times of d0 which are in dn > d1 <- d0 <- zoo(1:10) + 100 > dn <- - head(d0, 4) > > window(d1, time(dn)) <- coredata(dn) > > > > > cleanEx() > nameEx("xblocks") > ### * xblocks > > flush(stderr()); flush(stdout()) > > ### Name: xblocks > ### Title: Plot contiguous blocks along x axis. > ### Aliases: xblocks xblocks.default xblocks.zoo xblocks.ts > ### Keywords: dplot > > ### ** Examples > > ## example time series: > set.seed(0) > flow <- ts(filter(rlnorm(200, mean = 1), 0.8, method = "r")) > > ## highlight values above and below thresholds. > ## this draws on top using semi-transparent colors. > rgb <- hcl(c(0, 0, 260), c = c(100, 0, 100), l = c(50, 90, 50), alpha = 0.3) > plot(flow) > xblocks(flow > 30, col = rgb[1]) ## high values red > xblocks(flow < 15, col = rgb[3]) ## low value blue > xblocks(flow >= 15 & flow <= 30, col = rgb[2]) ## the rest gray > > ## same thing: > plot(flow) > xblocks(time(flow), cut(flow, c(0,15,30,Inf), labels = rev(rgb))) > > ## another approach is to plot blocks underneath without transparency. > plot(flow) > ## note that 'ifelse' keeps its result as class 'ts' > xblocks(ifelse(flow < mean(flow), hcl(0, 0, 90), hcl(0, 80, 70))) > ## need to redraw data series on top: > lines(flow) > box() > > ## for single series only: plot.default has a panel.first argument > plot(time(flow), flow, type = "l", + panel.first = xblocks(flow > 20, col = "lightgray")) > ## (see also the 'panel' argument for use with multiple series, below) > > ## insert some missing values > flow[c(1:10, 50:80, 100)] <- NA > > ## the default plot shows data coverage > ## (most useful when displaying multiple series, see below) > plot(flow) > xblocks(flow) > > ## can also show gaps: > plot(flow, type = "s") > xblocks(time(flow), is.na(flow), col = "gray") > > ## Example of alternating colors, here showing calendar months > flowdates <- as.Date("2000-01-01") + as.numeric(time(flow)) > flowz <- zoo(coredata(flow), flowdates) > plot(flowz) > xblocks(flowz, months, ## i.e. months(time(flowz)), + col = gray.colors(2, start = 0.7), border = "slategray") > lines(flowz) > > ## Example of multiple series. > ## set up example data > z <- ts(cbind(A = 0:5, B = c(6:7, NA, NA, 10:11), C = c(NA, 13:17))) > > ## show data coverage only (highlighting gaps) > plot(z, panel = function(x, ...) + xblocks(x, col = "darkgray")) > > ## draw gaps in darkgray > plot(z, type = "s", panel = function(x, ...) { + xblocks(time(x), is.na(x), col = "darkgray") + lines(x, ...); points(x) + }) > > ## Example of overlaying blocks from a different series. > ## Are US presidential approval ratings linked to sunspot activity? > ## Set block height to plot blocks along the bottom. > plot(presidents) > xblocks(sunspot.year > 50, height = 2) > > > > cleanEx() > nameEx("xyplot.zoo") > ### * xyplot.zoo > > flush(stderr()); flush(stdout()) > > ### Name: xyplot.zoo > ### Title: Plot zoo Series with Lattice > ### Aliases: xyplot.zoo xyplot.its xyplot.tis llines.zoo llines.its > ### llines.tis lpoints.zoo lpoints.its lpoints.tis ltext.zoo ltext.its > ### ltext.tis panel.lines.zoo panel.lines.ts panel.lines.its > ### panel.lines.tis panel.points.zoo panel.points.ts panel.points.its > ### panel.points.tis panel.text.zoo panel.text.ts panel.text.its > ### panel.text.tis panel.plot.default panel.plot.custom > ### panel.segments.zoo panel.segments.ts panel.segments.its > ### panel.segments.tis panel.rect.zoo panel.rect.ts panel.rect.its > ### panel.rect.tis panel.polygon.zoo panel.polygon.ts panel.polygon.its > ### panel.polygon.tis > ### Keywords: hplot ts > > ### ** Examples > > if(require("lattice") & require("grid")) { + + set.seed(1) + z <- zoo(cbind(a = 1:5, b = 11:15, c = 21:25) + rnorm(5)) + + # plot z using same Y axis on all plots + xyplot(z, scales = list(y = list(relation = "same", alternating = FALSE))) + + # plot a double-line-width running mean on the panel of b. + # Also add a grid. + # We show two ways to do it. + + # change strip background to levels of grey + # If you like the defaults, this can be omitted. + strip.background <- trellis.par.get("strip.background") + trellis.par.set(strip.background = list(col = grey(7:1/8))) + + + # Number 1. Using trellis.focus. + print( xyplot(z) ) + trellis.focus("panel", 1, 2, highlight = FALSE) + # (or just trellis.focus() for interactive use) + z.mean <- rollmean(z, 3) + panel.lines(z.mean[,2], lwd = 2) + panel.grid(h = 10, v = 10, col = "grey", lty = 3) + trellis.unfocus() + + # Number 2. Using a custom panel routine. + xyplot(z, panel = function(x, y, ...) { + if (packet.number() == 2) { + panel.grid(h = 10, v = 10, col = "grey", lty = 3) + panel.lines(rollmean(zoo(y, x), 3), lwd = 2) + } + panel.xyplot(x, y, ...) + }) + + # plot a light grey rectangle "behind" panel b + trellis.focus("panel", 1, 2) + grid.rect(x = 2, w = 1, default.units = "native", + gp = gpar(fill = "light grey")) + # do.call("panel.xyplot", trellis.panelArgs()) + do.call("panel.lines", trellis.panelArgs()[1:2]) + trellis.unfocus() + # a better method is to use a custom panel function. + # see also panel.xblocks() and layer() in the latticeExtra package. + + # same but make first panel twice as large as others + lopt <- list(layout.heights = list(panel = list(x = c(2,1,1)))) + xyplot(z, lattice.options = lopt) + # add a grid + update(trellis.last.object(), type = c("l", "g")) + + # Plot all in one panel. + xyplot(z, screens = 1) + # Same with default styles and auto.key: + xyplot(z, superpose = TRUE) + + # Plot first two columns in first panel and third column in second panel. + # Plot first series using points, second series using lines and third + # series via overprinting both lines and points + # Use colors 1, 2 and 3 for the three series (1=black, 2=red, 3=green) + # Make 2nd (lower) panel 3x the height of the 1st (upper) panel + # Also make the strip background orange. + p <- xyplot(z, screens = c(1,1,2), type = c("p", "l", "o"), col = 1:3, + par.settings = list(strip.background = list(col = "orange"))) + print(p, panel.height = list(y = c(1, 3), units = "null")) + + # Example of using a custom axis + # Months are labelled with smaller ticks for weeks and even smaller + # ticks for days. + Days <- seq(from = as.Date("2006-1-1"), to = as.Date("2006-8-8"), by = "day") + z1 <- zoo(seq(length(Days))^2, Days) + Months <- Days[format(Days, "%d") == "01"] + Weeks <- Days[format(Days, "%w") == "0"] + print( xyplot(z1, scales = list(x = list(at = Months))) ) + trellis.focus("panel", 1, 1, clip.off = TRUE) + panel.axis("bottom", check.overlap = TRUE, outside = TRUE, labels = FALSE, + tck = .7, at = as.numeric(Weeks)) + panel.axis("bottom", check.overlap = TRUE, outside = TRUE, labels = FALSE, + tck = .4, at = as.numeric(Days)) + trellis.unfocus() + + trellis.par.set(strip.background = strip.background) + + # separate the panels and suppress the ticks on very top + xyplot(z, between = list(y = 1), scales = list(tck = c(1,0))) + + # left strips but no top strips + xyplot(z, screens = colnames(z), strip = FALSE, strip.left = TRUE) + + # plot list of zoo objects using different x scales + z.l <- list( + zoo(cbind(a = rnorm(10), b = rnorm(10)), as.Date("2006-01-01") + 0:9), + zoo(cbind(c = rnorm(10), d = rnorm(10)), as.Date("2006-12-01") + 0:9) + ) + zm <- do.call(merge, z.l) + xlim <- lapply(zm, function(x) range(time(na.omit(x)))) + xyplot(zm, xlim = xlim, scale = list(relation = "free")) + # to avoid merging see xyplot.list() in the latticeExtra package. + + } Loading required package: lattice Loading required package: grid > > ## Not run: > ##D ## playwith (>= 0.9) > ##D library("playwith") > ##D > ##D z3 <- zoo(cbind(a = rnorm(100), b = rnorm(100) + 1), as.Date(1:100)) > ##D playwith(xyplot(z3), time.mode = TRUE) > ##D # hold down Shift key and drag to zoom in to a time period. > ##D # then use the horizontal scroll bar. > ##D > ##D # set custom labels; right click on points to view or add labels > ##D labs <- paste(round(z3,1), index(z3), sep = "@") > ##D trellis.par.set(user.text = list(cex = 0.7)) > ##D playwith(xyplot(z3, type = "o"), labels = labs) > ##D > ##D # this returns indexes into times of clicked points > ##D ids <- playGetIDs() > ##D z3[ids,] > ##D > ##D ## another example of using playwith with zoo > ##D # set up data > ##D dat <- zoo(matrix(rnorm(100*100),ncol=100), Sys.Date()+1:100) > ##D colnames(dat) <- paste("Series", 1:100) > ##D > ##D # This will give you a spin button to choose the column to plot, > ##D # and a button to print out the current series number. > ##D playwith(xyplot(dat[,c(1,i)]), parameters = list(i = 1:100, > ##D do_something = function(playState) print(playState$env$i)) > ##D > ## End(Not run) > > > > > cleanEx() detaching 'package:grid', 'package:lattice' > nameEx("yearmon") > ### * yearmon > > flush(stderr()); flush(stdout()) > > ### Name: yearmon > ### Title: An Index Class for Monthly Data > ### Aliases: yearmon as.yearmon as.yearmon.default as.yearmon.numeric > ### as.yearmon.integer as.yearmon.dates as.yearmon.Date > ### as.yearmon.timeDate as.yearmon.jul as.yearmon.POSIXt > ### as.yearmon.character as.yearmon.date as.yearmon.factor as.Date > ### as.Date.numeric as.Date.ts as.Date.yearmon as.POSIXct.yearmon > ### as.POSIXlt.yearmon as.numeric.yearmon as.character.yearmon > ### as.data.frame.yearmon c.yearmon cycle.yearmon format.yearmon > ### is.yearmon mean.yearmon print.yearmon range.yearmon summary.yearmon > ### unique.yearmon [.yearmon [[.yearmon MATCH.yearmon Ops.yearmon > ### Sys.yearmon -.yearmon xtfrm.yearmon > ### Keywords: ts > > ### ** Examples > > x <- as.yearmon(2000 + seq(0, 23)/12) > x [1] "Jan 2000" "Feb 2000" "Mar 2000" "Apr 2000" "May 2000" "Jun 2000" [7] "Jul 2000" "Aug 2000" "Sep 2000" "Oct 2000" "Nov 2000" "Dec 2000" [13] "Jan 2001" "Feb 2001" "Mar 2001" "Apr 2001" "May 2001" "Jun 2001" [19] "Jul 2001" "Aug 2001" "Sep 2001" "Oct 2001" "Nov 2001" "Dec 2001" > > as.yearmon("mar07", "%b%y") [1] "Mar 2007" > as.yearmon("2007-03-01") [1] "Mar 2007" > as.yearmon("2007-12") [1] "Dec 2007" > > # returned Date is the fraction of the way through > # the period given by frac (= 0 by default) > as.Date(x) [1] "2000-01-01" "2000-02-01" "2000-03-01" "2000-04-01" "2000-05-01" [6] "2000-06-01" "2000-07-01" "2000-08-01" "2000-09-01" "2000-10-01" [11] "2000-11-01" "2000-12-01" "2001-01-01" "2001-02-01" "2001-03-01" [16] "2001-04-01" "2001-05-01" "2001-06-01" "2001-07-01" "2001-08-01" [21] "2001-09-01" "2001-10-01" "2001-11-01" "2001-12-01" > as.Date(x, frac = 1) [1] "2000-01-31" "2000-02-29" "2000-03-31" "2000-04-30" "2000-05-31" [6] "2000-06-30" "2000-07-31" "2000-08-31" "2000-09-30" "2000-10-31" [11] "2000-11-30" "2000-12-31" "2001-01-31" "2001-02-28" "2001-03-31" [16] "2001-04-30" "2001-05-31" "2001-06-30" "2001-07-31" "2001-08-31" [21] "2001-09-30" "2001-10-31" "2001-11-30" "2001-12-31" > as.POSIXct(x) [1] "2000-01-01 01:00:00 CET" "2000-02-01 01:00:00 CET" [3] "2000-03-01 01:00:00 CET" "2000-04-01 02:00:00 CEST" [5] "2000-05-01 02:00:00 CEST" "2000-06-01 02:00:00 CEST" [7] "2000-07-01 02:00:00 CEST" "2000-08-01 02:00:00 CEST" [9] "2000-09-01 02:00:00 CEST" "2000-10-01 02:00:00 CEST" [11] "2000-11-01 01:00:00 CET" "2000-12-01 01:00:00 CET" [13] "2001-01-01 01:00:00 CET" "2001-02-01 01:00:00 CET" [15] "2001-03-01 01:00:00 CET" "2001-04-01 02:00:00 CEST" [17] "2001-05-01 02:00:00 CEST" "2001-06-01 02:00:00 CEST" [19] "2001-07-01 02:00:00 CEST" "2001-08-01 02:00:00 CEST" [21] "2001-09-01 02:00:00 CEST" "2001-10-01 02:00:00 CEST" [23] "2001-11-01 01:00:00 CET" "2001-12-01 01:00:00 CET" > > # given a Date, x, return the Date of the next Friday > nextfri <- function(x) 7 * ceiling(as.numeric(x - 1)/7) + as.Date(1) > > # given a Date, d, return the same Date in the following month > # Note that as.Date.yearmon gives first Date of the month. > d <- as.Date("2005-1-1") + seq(0,90,30) > next.month <- function(d) as.Date(as.yearmon(d) + 1/12) + + as.numeric(d - as.Date(as.yearmon(d))) > next.month(d) [1] "2005-02-01" "2005-03-03" "2005-04-02" "2005-05-01" > > # 3rd Friday in last month of the quarter of Date x > as.Date(as.yearmon(as.yearqtr(x)) + 2/12) + 14 [1] "2000-03-15" "2000-03-15" "2000-03-15" "2000-06-15" "2000-06-15" [6] "2000-06-15" "2000-09-15" "2000-09-15" "2000-09-15" "2000-12-15" [11] "2000-12-15" "2000-12-15" "2001-03-15" "2001-03-15" "2001-03-15" [16] "2001-06-15" "2001-06-15" "2001-06-15" "2001-09-15" "2001-09-15" [21] "2001-09-15" "2001-12-15" "2001-12-15" "2001-12-15" > > z <- zoo(rnorm(24), x, frequency = 12) > z Jan 2000 Feb 2000 Mar 2000 Apr 2000 May 2000 Jun 2000 -0.62645381 0.18364332 -0.83562861 1.59528080 0.32950777 -0.82046838 Jul 2000 Aug 2000 Sep 2000 Oct 2000 Nov 2000 Dec 2000 0.48742905 0.73832471 0.57578135 -0.30538839 1.51178117 0.38984324 Jan 2001 Feb 2001 Mar 2001 Apr 2001 May 2001 Jun 2001 -0.62124058 -2.21469989 1.12493092 -0.04493361 -0.01619026 0.94383621 Jul 2001 Aug 2001 Sep 2001 Oct 2001 Nov 2001 Dec 2001 0.82122120 0.59390132 0.91897737 0.78213630 0.07456498 -1.98935170 > as.ts(z) Jan Feb Mar Apr May Jun 2000 -0.62645381 0.18364332 -0.83562861 1.59528080 0.32950777 -0.82046838 2001 -0.62124058 -2.21469989 1.12493092 -0.04493361 -0.01619026 0.94383621 Jul Aug Sep Oct Nov Dec 2000 0.48742905 0.73832471 0.57578135 -0.30538839 1.51178117 0.38984324 2001 0.82122120 0.59390132 0.91897737 0.78213630 0.07456498 -1.98935170 > > ## convert data fram to multivariate monthly "ts" series > ## 1.read raw data > Lines.raw <- "ID Date Count + 123 20 May 1999 1 + 123 21 May 1999 3 + 222 1 Feb 2000 2 + 222 3 Feb 2000 4 + " > DF <- read.table(textConnection(Lines.raw), skip = 1, + col.names = c("ID", "d", "b", "Y", "Count")) > ## 2. fix raw date > DF$yearmon <- as.yearmon(paste(DF$b, DF$Y), "%b %Y") > ## 3. aggregate counts over months, convert to zoo and merge over IDs > ag <- function(DF) aggregate(zoo(DF$Count), DF$yearmon, sum) > z <- do.call("merge.zoo", lapply(split(DF, DF$ID), ag)) > ## 4. convert to "zooreg" and then to "ts" > frequency(z) <- 12 > as.ts(z) 123 222 May 1999 4 NA Jun 1999 NA NA Jul 1999 NA NA Aug 1999 NA NA Sep 1999 NA NA Oct 1999 NA NA Nov 1999 NA NA Dec 1999 NA NA Jan 2000 NA NA Feb 2000 NA 6 > > xx <- zoo(seq_along(x), x) > > ## aggregating over year > as.year <- function(x) as.numeric(floor(as.yearmon(x))) > aggregate(xx, as.year, mean) 2000 2001 6.5 18.5 > > > > > cleanEx() > nameEx("yearqtr") > ### * yearqtr > > flush(stderr()); flush(stdout()) > > ### Name: yearqtr > ### Title: An Index Class for Quarterly Data > ### Aliases: yearqtr as.yearqtr as.yearqtr.default as.yearqtr.numeric > ### as.yearqtr.integer as.yearqtr.date as.yearqtr.dates as.yearqtr.Date > ### as.yearqtr.timeDate as.yearqtr.jul as.yearqtr.POSIXt > ### as.yearqtr.character as.yearqtr.factor as.yearqtr.yearqtr > ### as.Date.yearqtr as.POSIXct.yearqtr as.POSIXlt.yearqtr > ### as.numeric.yearqtr as.character.yearqtr as.data.frame.yearqtr > ### c.yearqtr cycle.yearqtr format.yearqtr is.numeric.yearqtr > ### mean.yearqtr print.yearqtr range.yearqtr summary.yearqtr > ### unique.yearqtr [.yearqtr [[.yearqtr MATCH.yearqtr Ops.yearqtr > ### Summary.yearqtr Sys.yearqtr -.yearqtr xtfrm.yearqtr > ### Keywords: ts > > ### ** Examples > > x <- as.yearqtr(2000 + seq(0, 7)/4) > x [1] "2000 Q1" "2000 Q2" "2000 Q3" "2000 Q4" "2001 Q1" "2001 Q2" "2001 Q3" [8] "2001 Q4" > > format(x, "%Y Quarter %q") [1] "2000 Quarter 1" "2000 Quarter 2" "2000 Quarter 3" "2000 Quarter 4" [5] "2001 Quarter 1" "2001 Quarter 2" "2001 Quarter 3" "2001 Quarter 4" > as.yearqtr("2001 Q2") [1] "2001 Q2" > as.yearqtr("2001 q2") # same [1] "2001 Q2" > as.yearqtr("2001-2") # same [1] "2001 Q2" > > # returned Date is the fraction of the way through > # the period given by frac (= 0 by default) > dd <- as.Date(x) > format.yearqtr(dd) [1] "2000 Q1" "2000 Q2" "2000 Q3" "2000 Q4" "2001 Q1" "2001 Q2" "2001 Q3" [8] "2001 Q4" > as.Date(x, frac = 1) [1] "2000-03-31" "2000-06-30" "2000-09-30" "2000-12-31" "2001-03-31" [6] "2001-06-30" "2001-09-30" "2001-12-31" > as.POSIXct(x) [1] "2000-01-01 01:00:00 CET" "2000-04-01 02:00:00 CEST" [3] "2000-07-01 02:00:00 CEST" "2000-10-01 02:00:00 CEST" [5] "2001-01-01 01:00:00 CET" "2001-04-01 02:00:00 CEST" [7] "2001-07-01 02:00:00 CEST" "2001-10-01 02:00:00 CEST" > > zz <- zoo(rnorm(8), x, frequency = 4) > zz 2000 Q1 2000 Q2 2000 Q3 2000 Q4 2001 Q1 2001 Q2 2001 Q3 -0.6264538 0.1836433 -0.8356286 1.5952808 0.3295078 -0.8204684 0.4874291 2001 Q4 0.7383247 > as.ts(zz) Qtr1 Qtr2 Qtr3 Qtr4 2000 -0.6264538 0.1836433 -0.8356286 1.5952808 2001 0.3295078 -0.8204684 0.4874291 0.7383247 > > > > > cleanEx() > nameEx("zoo") > ### * zoo > > flush(stderr()); flush(stdout()) > > ### Name: zoo > ### Title: Z's Ordered Observations > ### Aliases: zoo with.zoo range.zoo print.zoo as.zoo.factor summary.zoo > ### str.zoo is.zoo [.zoo [<-.zoo $.zoo $<-.zoo subset.zoo head.zoo > ### tail.zoo Ops.zoo t.zoo cumsum.zoo cumprod.zoo cummin.zoo cummax.zoo > ### mean.zoo median.zoo na.contiguous na.contiguous.data.frame > ### na.contiguous.list na.contiguous.default na.contiguous.zoo scale.zoo > ### xtfrm.zoo names.zoo names<-.zoo quantile.zoo rev.zoo transform.zoo > ### index2char index2char.default index2char.numeric head.ts tail.ts > ### ifelse.zoo > ### Keywords: ts > > ### ** Examples > > ## simple creation and plotting > x.Date <- as.Date("2003-02-01") + c(1, 3, 7, 9, 14) - 1 > x <- zoo(rnorm(5), x.Date) > plot(x) > time(x) [1] "2003-02-01" "2003-02-03" "2003-02-07" "2003-02-09" "2003-02-14" > > ## subsetting with numeric indexes > x[c(2, 4)] 2003-02-03 2003-02-09 0.1836433 1.5952808 > ## subsetting with index class > x[as.Date("2003-02-01") + c(2, 8)] 2003-02-03 2003-02-09 0.1836433 1.5952808 > > ## different classes of indexes/times can be used, e.g. numeric vector > x <- zoo(rnorm(5), c(1, 3, 7, 9, 14)) > ## subsetting with numeric indexes then uses observation numbers > x[c(2, 4)] 3 9 0.4874291 0.5757814 > ## subsetting with index class can be enforced by I() > x[I(c(3, 9))] 3 9 0.4874291 0.5757814 > > ## visualization > plot(x) > ## or POSIXct > y.POSIXct <- ISOdatetime(2003, 02, c(1, 3, 7, 9, 14), 0, 0, 0) > y <- zoo(rnorm(5), y.POSIXct) > plot(y) > > ## create a constant series > z <- zoo(1, seq(4)[-2]) > > ## create a 0-dimensional zoo series > z0 <- zoo(, 1:4) > > ## create a 2-dimensional zoo series > z2 <- zoo(matrix(1:12, 4, 3), as.Date("2003-01-01") + 0:3) > > ## create a factor zoo object > fz <- zoo(gl(2,5), as.Date("2004-01-01") + 0:9) > > ## create a zoo series with 0 columns > z20 <- zoo(matrix(nrow = 4, ncol = 0), 1:4) > > ## arithmetic on zoo objects intersects them first > x1 <- zoo(1:5, 1:5) > x2 <- zoo(2:6, 2:6) > 10 * x1 + x2 2 3 4 5 22 33 44 55 > > ## $ extractor for multivariate zoo series with column names > z <- zoo(cbind(foo = rnorm(5), bar = rnorm(5))) > z$foo 1 2 3 4 5 -0.04493361 -0.01619026 0.94383621 0.82122120 0.59390132 > z$xyz <- zoo(rnorm(3), 2:4) > z foo bar xyz 1 -0.04493361 0.91897737 NA 2 -0.01619026 0.78213630 -0.05612874 3 0.94383621 0.07456498 -0.15579551 4 0.82122120 -1.98935170 -1.47075238 5 0.59390132 0.61982575 NA > > ## add comments to a zoo object > comment(x1) <- c("This is a very simple example of a zoo object.", + "It can be recreated using this R code: example(zoo)") > ## comments are not output by default but are still there > x1 1 2 3 4 5 1 2 3 4 5 > comment(x1) [1] "This is a very simple example of a zoo object." [2] "It can be recreated using this R code: example(zoo)" > > # ifelse does not work with zoo but this works > # to create a zoo object which equals x1 at > # time i if x1[i] > x1[i-1] and 0 otherwise > (diff(x1) > 0) * x1 2 3 4 5 2 3 4 5 > > ## zoo series with duplicated indexes > z3 <- zoo(1:8, c(1, 2, 2, 2, 3, 4, 5, 5)) Warning in zoo(1:8, c(1, 2, 2, 2, 3, 4, 5, 5)) : some methods for "zoo" objects do not work if the index entries in 'order.by' are not unique > plot(z3) > ## remove duplicated indexes by averaging > lines(aggregate(z3, index(z3), mean), col = 2) > ## or by using the last observation > lines(aggregate(z3, index(z3), tail, 1), col = 4) > > ## x1[x1 > 3] is not officially supported since > ## x1 > 3 is of class "zoo", not "logical". > ## Use one of these instead: > x1[which(x1 > 3)] 4 5 4 5 > x1[coredata(x1 > 3)] 4 5 4 5 > x1[as.logical(x1 > 3)] 4 5 4 5 > subset(x1, x1 > 3) 4 5 4 5 > > ## any class supporting the methods discussed can be used > ## as an index class. Here are examples using complex numbers > ## and letters as the time class. > > z4 <- zoo(11:15, complex(real = c(1, 3, 4, 5, 6), imag = c(0, 1, 0, 0, 1))) > merge(z4, lag(z4)) z4 lag(z4) 1+0i 11 12 3+1i 12 13 4+0i 13 14 5+0i 14 15 6+1i 15 NA > > z5 <- zoo(11:15, letters[1:5]) > merge(z5, lag(z5)) z5 lag(z5) a 11 12 b 12 13 c 13 14 d 14 15 e 15 NA > > # index values relative to 2001Q1 > zz <- zooreg(cbind(a = 1:10, b = 11:20), start = as.yearqtr(2000), freq = 4) > zz[] <- mapply("/", as.data.frame(zz), coredata(zz[as.yearqtr("2001Q1")])) > > > ## even though time index must be unique zoo (and read.zoo) > ## will both allow creation of such illegal objects with > ## a warning (rather than ana error) to give the user a > ## chance to fix them up. Extracting and replacing times > ## and aggregate.zoo will still work. > ## Not run: > ##D # this gives a warning > ##D # and then creates an illegal zoo object > ##D z6 <- zoo(11:15, c(1, 1, 2, 2, 5)) > ##D z6 > ##D > ##D # fix it up by averaging duplicates > ##D aggregate(z6, identity, mean) > ##D > ##D # or, fix it up by taking last in each set of duplicates > ##D aggregate(z6, identity, tail, 1) > ##D > ##D # fix it up via interpolation of duplicate times > ##D time(z6) <- na.approx(ifelse(duplicated(time(z6)), NA, time(z6)), na.rm = FALSE) > ##D # if there is a run of equal times at end they > ##D # wind up as NAs and we cannot have NA times > ##D z6 <- z6[!is.na(time(z6))] > ##D z6 > ##D > ##D x1. <- x1 <- zoo (matrix (1:12, nrow = 3), as.Date("2008-08-01") + 0:2) > ##D colnames (x1) <- c ("A", "B", "C", "D") > ##D x2 <- zoo (matrix (1:12, nrow = 3), as.Date("2008-08-01") + 1:3) > ##D colnames (x2) <- c ("B", "C", "D", "E") > ##D > ##D both.dates = as.Date (intersect (index (t1), index (t2))) > ##D both.cols = intersect (colnames (t1), colnames (t2)) > ##D > ##D x1[both.dates, both.cols] > ##D ## there is "[.zoo" but no "[<-.zoo" however four of the following > ##D ## five examples work > ##D > ##D ## wrong > ##D ## x1[both.dates, both.cols] <- x2[both.dates, both.cols] > ##D > ##D # 4 correct alternatives > ##D # #1 > ##D window(x1, both.dates)[, both.cols] <- x2[both.dates, both.cols] > ##D > ##D # #2. restore x1 and show a different way > ##D x1 <- x1. > ##D window(x1, both.dates)[, both.cols] <- window(x2, both.dates)[, both.cols] > ##D > ##D # #3. restore x1 and show a different way > ##D x1 <- x1. > ##D x1[time(x1) ##D > ##D > ##D # #4. restore x1 and show a different way > ##D x1 <- x1. > ##D x1[time(x1) ##D > ##D > ## End(Not run) > > > > > cleanEx() > nameEx("zooreg") > ### * zooreg > > flush(stderr()); flush(stdout()) > > ### Name: zooreg > ### Title: Regular zoo Series > ### Aliases: zooreg frequency.zooreg frequency.zoo deltat.zooreg deltat.zoo > ### cycle.zooreg cycle.zoo as.zooreg as.zooreg.default as.zooreg.ts > ### as.zooreg.its as.zooreg.xts as.ts.zooreg as.zoo.zooreg as.zooreg.zoo > ### index<-.zooreg time<-.zooreg lag.zooreg > ### Keywords: ts > > ### ** Examples > > ## equivalent specifications of a quarterly series > ## starting in the second quarter of 1959. > zooreg(1:10, frequency = 4, start = c(1959, 2)) 1959(2) 1959(3) 1959(4) 1960(1) 1960(2) 1960(3) 1960(4) 1961(1) 1961(2) 1961(3) 1 2 3 4 5 6 7 8 9 10 > as.zoo(ts(1:10, frequency = 4, start = c(1959, 2))) 1959(2) 1959(3) 1959(4) 1960(1) 1960(2) 1960(3) 1960(4) 1961(1) 1961(2) 1961(3) 1 2 3 4 5 6 7 8 9 10 > zoo(1:10, seq(1959.25, 1961.5, by = 0.25), frequency = 4) 1959(2) 1959(3) 1959(4) 1960(1) 1960(2) 1960(3) 1960(4) 1961(1) 1961(2) 1961(3) 1 2 3 4 5 6 7 8 9 10 > > ## use yearqtr class for indexing the same series > z <- zoo(1:10, yearqtr(seq(1959.25, 1961.5, by = 0.25)), frequency = 4) > z 1959 Q2 1959 Q3 1959 Q4 1960 Q1 1960 Q2 1960 Q3 1960 Q4 1961 Q1 1961 Q2 1961 Q3 1 2 3 4 5 6 7 8 9 10 > z[-(3:4)] 1959 Q2 1959 Q3 1960 Q2 1960 Q3 1960 Q4 1961 Q1 1961 Q2 1961 Q3 1 2 5 6 7 8 9 10 > > ## create a regular series with a "Date" index > zooreg(1:5, start = as.Date("2000-01-01")) 2000-01-01 2000-01-02 2000-01-03 2000-01-04 2000-01-05 1 2 3 4 5 > ## or with "yearmon" index > zooreg(1:5, end = yearmon(2000)) Jan 1996 Jan 1997 Jan 1998 Jan 1999 Jan 2000 1 2 3 4 5 > > ## lag and diff (as diff is defined in terms of lag) > ## act differently on zoo and zooreg objects! > ## lag.zoo moves a point to the adjacent time whereas > ## lag.zooreg moves a point by deltat > x <- c(1, 2, 3, 6) > zz <- zoo(x, x) > zr <- as.zooreg(zz) > lag(zz, k = -1) 2 3 6 1 2 3 > lag(zr, k = -1) 2 3 4 7 1 2 3 6 > diff(zz) 2 3 6 1 1 3 > diff(zr) 2 3 1 1 > > ## lag.zooreg wihtout and with na.pad > lag(zr, k = -1) 2 3 4 7 1 2 3 6 > lag(zr, k = -1, na.pad = TRUE) 1 2 3 4 6 7 NA 1 2 3 NA 6 > > ## standard methods available for regular series > frequency(z) [1] 4 > deltat(z) [1] 0.25 > cycle(z) 1959 Q2 1959 Q3 1959 Q4 1960 Q1 1960 Q2 1960 Q3 1960 Q4 1961 Q1 1961 Q2 1961 Q3 2 3 4 1 2 3 4 1 2 3 > cycle(z[-(3:4)]) 1959 Q2 1959 Q3 1960 Q2 1960 Q3 1960 Q4 1961 Q1 1961 Q2 1961 Q3 2 3 2 3 4 1 2 3 > > zz <- zoo(1:6, as.Date(c("1960-01-29", "1960-02-29", "1960-03-31", + "1960-04-29", "1960-05-31", "1960-06-30"))) > # this converts zz to "zooreg" and then to "ts" expanding it to a daily > # series which is 154 elements long, most with NAs. > ## Not run: > ##D length(as.ts(zz)) # 154 > ## End(Not run) > # probably a monthly "ts" series rather than a daily one was wanted. > # This variation of the last line gives a result only 6 elements long. > length(as.ts(aggregate(zz, as.yearmon, c))) # 6 [1] 6 > > zzr <- as.zooreg(zz) > > dd <- as.Date(c("2000-01-01", "2000-02-01", "2000-03-01", "2000-04-01")) > zrd <- as.zooreg(zoo(1:4, dd)) > > > > > ### *