[Xts-commits] r787 - in pkg/xts: . R inst/doc vignettes
noreply at r-forge.r-project.org
noreply at r-forge.r-project.org
Sun Aug 25 16:06:42 CEST 2013
Author: jryan
Date: 2013-08-25 16:06:42 +0200 (Sun, 25 Aug 2013)
New Revision: 787
Added:
pkg/xts/vignettes/
pkg/xts/vignettes/xts-faq.Rnw
pkg/xts/vignettes/xts.Rnw
Removed:
pkg/xts/inst/doc/xts-faq.Rnw
pkg/xts/inst/doc/xts.Rnw
Modified:
pkg/xts/R/origin.fix.R
pkg/xts/R/plot.R
Log:
o more fixes for CRAN checks - new vignettes/ dir and
removed some old ::: usages (which are enough to cause NOTEs)..
Modified: pkg/xts/R/origin.fix.R
===================================================================
--- pkg/xts/R/origin.fix.R 2013-08-20 03:47:23 UTC (rev 786)
+++ pkg/xts/R/origin.fix.R 2013-08-25 14:06:42 UTC (rev 787)
@@ -50,7 +50,7 @@
as.POSIXlt.Date <- function(x, ...)
{
- as.POSIXlt(xts:::as.POSIXct.Date(x))
+ as.POSIXlt(as.POSIXct.Date(x))
}
#as.POSIXct.yearmon <- function(x, ...)
Modified: pkg/xts/R/plot.R
===================================================================
--- pkg/xts/R/plot.R 2013-08-20 03:47:23 UTC (rev 786)
+++ pkg/xts/R/plot.R 2013-08-25 14:06:42 UTC (rev 787)
@@ -81,7 +81,7 @@
if( identical(getxvalues(last.plot), getxvalues(recordPlot())) ) {
lines.default(getxvalues(recordPlot()),
x, ...)
- } else zoo:::lines.zoo(x, ...)
+ } else lines(as.zoo(x), ...)
assign(".plot.xts",recordPlot(),.xtsEnv)
}
Deleted: pkg/xts/inst/doc/xts-faq.Rnw
===================================================================
--- pkg/xts/inst/doc/xts-faq.Rnw 2013-08-20 03:47:23 UTC (rev 786)
+++ pkg/xts/inst/doc/xts-faq.Rnw 2013-08-25 14:06:42 UTC (rev 787)
@@ -1,274 +0,0 @@
-%\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}
-
-%% -*- encoding: utf-8 -*-
-%\VignetteIndexEntry{xts FAQ}
-\documentclass{article}
-%
-\usepackage{Rd}
-\usepackage{Sweave}
-%%\encoding{UTF-8}
-%%\usepackage[UTF-8]{inputenc}
-%
-\newcommand{\q}[1]{\section*{#1}\addcontentsline{toc}{subsection}{#1}}
-
-\author{\pkg{xts} Development Team}
-%\Plainauthor{xts Development Team}
-%-%-%-%-% Need to add footnote thanking Alberto Giannetti for his
-%-%-%-%-% contribution of many useful questions.
-
-%\Address{
-% \pkg{xts} Development Team\\
-% \proglang{R}-Forge: \url{http://r-forge.r-project.org/projects/xts/}\\
-% Comprehensive \proglang{R} Archive Network: \url{http://cran.r-project.org/package=xts}
-%}
-
-\title{\pkg{xts} FAQ}
-%\Plaintitle{xts FAQ}
-
-%\Keywords{irregular time series, time index, daily data, weekly data, returns}
-
-%\Abstract{
-% This is a collection of frequently asked questions (FAQ) about the
-% \pkg{xts} package together with their answers.
-%}
-
-
-\begin{document}
-
-\SweaveOpts{concordance=TRUE, engine=R, eps=FALSE}
-%\SweaveOpts{engine=R, eps=FALSE}
-
-<<preliminaries, echo=FALSE, results=hide>>=
-library("xts")
-Sys.setenv(TZ = "GMT")
-@
-
-\makeatletter
-\makeatother
-\maketitle
-
-\tableofcontents
-
-\q{What is \pkg{xts}?}
-%
-\pkg{xts} is an \pkg{R} package offering a number of functionalities to work on
-time-indexed data. \pkg{xts} extends \pkg{\pkg{zoo}}, another popular package
-for time-series analysis.
-% should point to the zoo FAQ here (or at some early point)
-
-\q{Why should I use \pkg{xts} rather than \pkg{zoo} or another time-series
-package?}
-%
-The main benefit of \pkg{xts} is its seamless compatibility with other packages
-using different time-series classes (\pkg{timeSeries}, \pkg{zoo}, ...). In
-addition \pkg{xts} allows the user to add custom attributes to any object. For
-more information check the \pkg{xts} Vignette Introduction.
-
-\q{How do I install \pkg{xts}?}
-%
-\pkg{xts} depends on \pkg{zoo} and some other packages. You should be able to
-install \pkg{xts} and all the other required components by simply calling
-\code{install.packages('pkg')} from your \pkg{R} prompt.
-
-\q{I have multiple .csv time-series files that I need to load in a single
-\pkg{xts} matrix. What is the most efficient way to import the files?}
-%
-If the files series have the same format, load them with \code{read.csv()} and
-then call \code{rbind()} to join the series together:
-<<eval=FALSE>>=
-filenames <- c("a.csv", "b.csv", "c.csv")
-l <- lapply(filenames, read.csv)
-do.call("rbind", l)
-@
-
-\q{Why is \pkg{xts} implemented as a matrix rather than a data frame?}
-%
-\pkg{xts} uses a matrix rather than data.frame because:
-\begin{enumerate}
- \item It is a subclass of \pkg{zoo}, and that's how \pkg{zoo} objects are
- structured; and
- \item matrix objects have much better performance than data.frames.
-\end{enumerate}
-
-\q{How can I simplify the syntax of my \pkg{xts} matrix column names?}
-%
-\code{with()} allows to enter the matrix name avoiding the full square brackets
-syntax. For example:
-<<eval=FALSE>>=
-lm(myxts[, "Res"] ~ myxts[, "ThisVar"] + myxts[, "ThatVar"])
-@
-can be converted to
-<<eval=FALSE>>=
-with(myxts, lm(Res ~ ThisVar + ThatVar))
-@
-
-\q{How can I replace the 0s in an \pkg{xts} object with the last non-zero value
-in the series?}
-%
-Use \code{na.locf}:
-<<>>=
-x <- .xts(c(1, 2, 3, 0, 0, 0), 1:6)
-x[x==0] <- NA
-na.locf(x)
-x
-@
-
-\q{How do I create an \pkg{xts} index with millisecond precision?}
-%
-Milliseconds in \pkg{xts} are stored as decimal values. This example builds a
-series spaced by 100 milliseconds, starting at the current system time:
-<<>>=
-data(sample_matrix)
-sample.xts = xts(sample_matrix, Sys.time() + seq(0, by = 0.1, length = 180))
-@
-
-\q{OK, so now I have my millisecond series but I still can't see the
-milliseconds displayed. What went wrong?}
-%
-Set the \code{digits.secs} option to some sub-second precision. Continuing from
-the previous example, if you are interested in milliseconds:
-<<>>=
-options(digits.secs = 3)
-head(sample.xts)
-@
-
-\q{I set \code{digits.sec = 3}, but \pkg{R} doesn't show the values correctly.}
-%
-Sub-second values are stored in floating point format with microseconds
-precision. Setting the precision to only 3 decimal hides the full index value
-in microseconds and might be tricky to interpret depending how the machine
-rounds the millisecond (3rd) digit. Set the digits.secs options to a value
-higher than 3 or use the \code{as.numeric()} 'digits' parameter to display the
-full value. For example:
-<<>>=
-print(as.numeric(as.POSIXlt("2012-03-20 09:02:50.001")), digits = 20)
-@
-
-\q{I am using \code{apply()} to run a custom function on my \pkg{xts} series.
-Why the returned matrix has different dimensions than the original one?}
-%
-When working on rows, \code{apply()} returns a transposed version of the
-original matrix. Simply call \code{t()} on the returned matrix to restore the
-original dimensions:
-<<eval=FALSE>>=
-myxts.2 <- xts(t(apply(myxts, 1 , myfun)), index(myxts))
-@
-
-\q{I have an \pkg{xts} matrix with multiple days of data at various
-frequencies. For example, day 1 might contain 10 different rows of 1 minute
-observations, while day 2 contains 20 observations. How can I process all
-observations for each day and return the summary daily statistics in a new
-matrix?}
-%
-First split the source matrix in day subsets, then call \code{rbind()} to join
-the processed day statistics together:
-<<eval=FALSE>>=
-do.call(rbind, lapply(split(myxts,"days"), myfun))
-@
-
-\q{How can I process daily data for a specific time subset?}
-%
-First extract the time range you want to work on, then apply the daily function:
-<<eval=FALSE>>=
-rt <- r['T16:00/T17:00','Value']
-rd <- apply.daily(rt, function(x) xts(t(quantile(x,0.9)), end(x)))
-@
-
-\q{How can I process my data in 3-hour blocks, regardless of the begin/end time?
- I also want to add observations at the beginning and end of each discrete
- period if missing from the original time-series object.}
-%
-Use \code{align.time()} to set indexes in the periods you are interested in,
-then call \code{period.apply} to run your processing function:
-<<eval=FALSE>>=
-# align index into 3-hour blocks
-a <- align.time(s, n=60*60*3)
-# find the number of obs in each block
-count <- period.apply(a, endpoints(a, "hours", 3), length)
-# create an empty \pkg{xts} object with the desired index
-e <- xts(,seq(start(a),end(a),by="3 hours"))
-# merge the counts with the empty object and fill with zeros
-out <- merge(e,count,fill=0)
-@
-
-\q{Why do I get a \pkg{zoo} object when I call transform() on my \pkg{xts}
-matrix?}
-%
-There's no \pkg{xts} method for transform, so the \pkg{zoo} method is
-dispatched. The \pkg{zoo} method explicitly creates a new \pkg{zoo} object. To
-convert the transformed matrix back to an \pkg{xts} object wrap the transform
-call in \code{as.xts}:
-<<eval=FALSE>>=
-myxts = as.xts(transform(myxts, ABC = 1))
-@
-
-You might also have to reset the index timezone:
-<<eval=FALSE>>=
-indexTZ(myxts) = Sys.getenv("TZ")
-@
-
-\q{Why can't I use the \code{\&} operator in \pkg{xts} objects when querying
-dates?}
-%
-\code{"2011-09-21"} is not a logical vector and cannot be coerced to a logical
-vector. See \code{?"\&"} for details.
-
-\pkg{xts}' ISO-8601 style subsetting is nice, but there's nothing we can do to
-change the behavior of \code{.Primitive("\&")}. You can do something like this
-though:
-<<eval=FALSE>>=
-myts[myts$Symbol == "AAPL" & index(myts) == as.POSIXct("2011-09-21"),]
-@
-or:
-<<eval=FALSE>>=
-myts[myts$Symbol == "AAPL"]['2011-09-21']
-@
-
-\q{How do I subset an \pkg{xts} object to only include weekdays (excluding
-Saturday and Sundays)?}
-%
-Use \code{.indexwday()} to only include Mon-Fri days:
-<<>>=
-data(sample_matrix)
-sample.xts <- as.xts(sample_matrix, descr='my new xts object')
-x <- sample.xts['2007']
-x[.indexwday(x) %in% 1:5]
-@
-
-\q{I need to quickly convert a data-frame that contains the time-stamps in one
-of the columns. Using \code{as.xts(q)} returns an error. How do I build my
-\pkg{xts} object?}
-%
-The \pkg{xts}() constructor requires two arguments: a vector or a matrix
-carrying data and a vector of type \code{Date}, \code{POSIcXt}, \code{chron},
-\ldots supplying the time index information. If the time is set in one of the
-matrix columns, use this line:
-<<eval=FALSE>>=
-qxts = xts(q[,-1], order.by=q[,1])
-@
-
-\q{I have two time-series with different frequency. I want to combine the data
-into a single data frame, but the times are not exactly aligned. I want to have
-one row in the data frame for each ten minute period, with the time index
-showing the beginning of the time period.}
-%
-\code{align.time()} creates evenly spaced time-series from a set of indexes,
-\code{merge()} insure two time-series are combined in a single \pkg{xts} object
-with all original columns and indexes preserved. The new object has one entry
-for each timestamp from both series and values missing are replaced with
-\code{NA}s.
-<<eval=FALSE>>=
-xTemps <- align.time(xts(temps[,2],as.POSIXct(temps[,1])), n=600)
-xGas <- align.time(xts(gas[,2],as.POSIXct(gas[,1])), n=600)
-merge(xTemps,xGas)
-@
-
-\end{document}
Deleted: pkg/xts/inst/doc/xts.Rnw
===================================================================
--- pkg/xts/inst/doc/xts.Rnw 2013-08-20 03:47:23 UTC (rev 786)
+++ pkg/xts/inst/doc/xts.Rnw 2013-08-25 14:06:42 UTC (rev 787)
@@ -1,807 +0,0 @@
-%\VignetteIndexEntry{xts: Extensible Time Series}
-\documentclass{article}
-\usepackage{hyperref}
-\hypersetup{colorlinks,%
- citecolor=black,%
- linkcolor=blue,%
- urlcolor=blue,%
- }
-
-\title{\bf xts: Extensible Time Series }
-\author{Jeffrey A. Ryan \and Joshua M. Ulrich}
-\date{May 18, 2008}
-
-\begin{document}
-
-\maketitle
-\tableofcontents
-
-\section{Introduction}
-The statistical language {\tt R}~\cite{R}
- offers the time-series analyst a variety of mechanisms
-to both store and manage time-indexed data.
-Native {\tt R} classes potentially suitable
-for time-series data include {\tt data.frame}, {\tt matrix}, {\tt vector}, and
-{\tt ts} objects. Additional time-series tools have been subsequently introduced
-in contributed packages to
-handle some of the domain-specific shortcomings of the native {\tt R} classes.
-These include {\tt irts} from the {\tt tseries} package\cite{tseries},
-{\tt timeSeries} from the {\tt Rmetrics} bundle\cite{rmetrics}, and
-{\tt its}~\cite{its} and {\tt zoo}~\cite{zoo} from their
-respective packages. Each of these contributed classes provides unique solution
-to many of the issues
-related to working with time-series in R.
-
-While it seems a bit paradoxical with all the current options
-available, what {\tt R} really needed was one more
-time-series class. Why? Users of R have had many choices over the
-years for managing time-series data. This variety has meant that
-developers have had to pick and choose the classes they would support,
-or impose the necessary conversions upon the end-user. With the sheer
-magnitude of software packages available from CRAN, it has become a challenge
-for users and developers
-to select a time-series class that will manage the needs of the
-individual user, as well as remain compatible with the broadest audience.
-
-What may be sufficient for one use --- say a quick correlation matrix may be
-too limiting when more information needs to be incorporated
-in a complex calculation.
-This is especially true for functions that rely on time-based indexes to
-be manipulated or checked.
-
-The previous solution to managing different data needs often
-involved a series of {\tt as} calls,
-to coerce objects from one type to another. While this may
-be sufficient for many cases, it is less flexible than allowing the users
-to simply use the object they are accustomed to, or quite possibly require.
-Additionally, all current coercion methods fail to maintain the original
-object's data in its entirety. Converting from a {\tt timeSeries} class to
-{\tt zoo} would cause attributes such as
-{\em FinCenter}, {\em format}, and {\em recordIDs} to be lost.
-Converting back to a {\tt timeSeries} would then add new
-values different than the original.
-For many calculations that do not modify the data, this is most likely
-an acceptable side effect. For functions that convert data ---
-such as {\tt xts}'s {\tt to.period} --- it limits the value of the function,
-as the returned object is missing
-much of what may have been a factor in the original class consideration.
-
-One of the most important additions the new {\tt xts} class makes
-to the R user's
-workflow doesn't use {\tt xts} at all, at least not explicitly.
-By converting data to {\tt xts} inside a function, the function developer
-is guaranteed to have to only manage a single class of objects.
-It becomes unecessary to write specific methods to handle different data.
-While many functions do have
-methods to accommodate different classes, most do not. Before {\tt xts}, the
-{\tt chartSeries} function in the {\tt quantmod} package\cite{quantmod}
-was only able to handle {\tt zoo} objects well.
-Work had been done to allow for {\tt timeSeries} objects to be used as well, but
-many issues were still being worked out.
-With {\tt xts} now used internally, it is
-possible to use \emph{any} of R's time-series classes.
-Simultaneously saving development time and
-reducing the learning/using curve for the end user. The function now
-simply handles whatever time-series object it receives
-exactly as the user expects --- without complaint.
-More details, as well as examples of incorporating {\tt xts} into
-functions will be covered later in this document.
-
-While it may seem that {\tt xts} is primarily a tool
-to help make existing R code
-more user-friendly, the opportunity to add exciting
-(to software people) new functionality
-could not be passed up. To this end, {\tt xts}
-offers the user the ability to add
-custom attributes to any object --- during its construction
-or at any time thereafter. Additionally,
-by requiring that the index attribute be derived from one of
-R's existing time-based classes, {\tt xts} methods can
-make assumptions, while subsetting by time or date, that allow for
-much cleaner and accurate data manipulation.
-
-The remainder of this introduction will
-examine what an {\tt xts} object consists of and
-its basic usage, explain how developing with {\tt xts} can save
-package development time, and finally will demonstrate
-how to extend the class - informally
-and formally.
-
-\pagebreak
-\section{The structure of {\tt xts}}
-To understand a bit more of \emph{what an xts object can do}, it may
-be beneficial to know \emph{what an xts object is}. This section
-is intended to provide a quick overview of the basics of the
-class, as well as what features make it unique.
-
-\subsection{It's a {\tt zoo} in here}
-At the core of an {\tt xts} object is a {\tt zoo} object from the package of
-the same name. Simplified, this class contains an array of values
-comprising your data (often in matrix form) and an index
-attribute to provide information about
-the data's ordering. Most of the details surrounding zoo
-objects apply equally to xts. As it would be redundent to simply retell
-the excellent introductory zoo vignette, the reader is advised to
-read, absorb, and re-read that documentation to best
-understand the power of this class. The authors of the {\tt xts}
-package recognize that
-{\tt zoo}'s strength comes from its
-simplicity of use, as well as its overall flexibility. What motivated the
-{\tt xts} extension was a desire to have even more flexibility, while
-imposing reasonable constraints to make this class into a true time-based one.
-
-\subsection{{\tt xts} modifications}
-Objects of class {\tt xts} differ from objects of class
-{\tt zoo} in three key ways: the use of formal time-based
-classes for indexing,
-internal xts properties, and perhaps most uniquely
---- user-added attributes.
-
-\subsubsection*{True time-based indexes}
-To allow for functions that make use of {\tt xts} objects
-as a general time-series object - it was necessary to
-impose a simple rule on the class. The index of each
-{\tt xts} object \emph{must} be of a known and supported
-time or date class. At present this includes any one of
-the following - Date, POSIXct, chron, yearmon, yearqtr, or
-timeDate. The relative merits of each are left to
-the judgement of the user, though the first three are expected
-to be sufficient for most applications.
-
-\subsubsection*{Internal attributes: .CLASS, .ROWNAMES, etc.}
-In order for one major feature of the {\tt xts} class
-to be possible - the conversion and re-conversion of classes
-to and from {\tt xts} - certain elements must be preserved within
-the converted object. These are for internal use, and
-as such require little further explanation in an introductory
-document. Interested readers are invited to examine the source as
-well as read the developer documentation.
-
-\subsubsection*{xtsAttributes}
-This is what makes the xts class an \emph{extensible}
-time-series class. Arbitrary attributes may be assigned
-and removed from the object without causing issues with the data's display or
-otherwise. Additionally this is where \emph{other}
-class specific attributes (e.g. \emph{FinCenter} from {\tt timeSeries})
-are stored during conversion
-to an xts object so they may be restored with {\tt reclass}.
-
-\pagebreak
-\section{Using the {\tt xts} package}
-Just what is required to start using {\tt xts}? Nothing more
-than a simple conversion of your current time-series data with
-{\tt as.xts}, or the creation of a new object with the {\tt xts} constructor.
-
-\subsection{Creating data objects: {\tt as.xts} and {\tt xts}}
-There are two equally valid mechanisms to create an {\tt xts}
-object - coerce a supported time-series class to {\tt xts} with
-a call to {\tt as.xts} or create a new object from scratch
-with {\tt xts}.
-
-\subsubsection*{Converting your \emph{existing} time-series data: {\tt as.xts}}
-If you are already comfortable using a particular
-time-series class in {\tt R}, you can still access
-the functionality of {\tt xts} by converting your
-current objects.
-
-Presently it is possible to convert all the major
-time-series like classes in {\tt R} to {\tt xts}. This list
-includes objects of class:
-matrix, data.frame, ts, zoo, irts, its, and timeSeries.
-The new object will maintain all the necessary information
-needed to {\tt reclass} this object back to its
-original class if that is desired. Most classes
-after re-conversion will be identical to similar modifications
-on the original object, even
-after sub-setting or other changes while an {\tt xts} object.
-
-<<a>>=
-require(xts)
-data(sample_matrix)
-class(sample_matrix)
-str(sample_matrix)
-matrix_xts <- as.xts(sample_matrix,dateFormat='Date')
-str(matrix_xts)
-df_xts <- as.xts(as.data.frame(sample_matrix),
- important='very important info!')
-str(df_xts)
-@
-
-A few comments about the above. {\tt as.xts} takes different arguments, depending
-on the original object to be converted. Some classes do not contain enough
-information to infer a time-date class. If that is the case, POSIXct is used by
-default. This is the case with both matrix and data.frame objects. In the preceding
-examples we first requested that the new date format be of type 'Date'. The
-second example was left to the default {\tt xts} method
-with a custom attribute added.
-
-\subsubsection*{Creating new data: the {\tt xts} constructor}
-Data objects can also be constructed directly from raw data with
-the {\tt xts} constructor function, in essentially the same way
-a {\tt zoo} object is created with the exception that at present
-there is no equivelant {\tt zooreg} class.
-
-<<xtsconstructor>>=
-xts(1:10, Sys.Date()+1:10)
-@
-
-\subsection{{\tt xts} methods}
-There is a full complement of standard methods to make use of the features
-present in {\tt xts} objects. The generic methods currently
-extended to {\tt xts} include ``{\tt [}'',
-{\tt cbind}, {\tt rbind}, {\tt c}, {\tt str}, {\tt Ops},
-{\tt print}, {\tt na.omit}, {\tt time}, {\tt index},
-{\tt plot} and {\tt coredata}. In addition, most methods that can accept
-zoo or matrix objects will simply work as expected.
-
-A quick tour of some of the methods leveraged by {\tt xts}
-will be presented here, including subsetting via ``{\tt [}'',
-indexing objects with {\tt indexClass} and {\tt convertIndex},
-and a quick look at plotting {\tt xts} objects with the {\tt plot}
-function.
-
-\subsubsection*{Subsetting}
-The most noticable difference in the behavior of \texttt{xts} objects
-will be apparent in the use of the ``{\tt [}'' operator. Using
-special notation, one can use date-like strings to extract
-data based on the time-index. Using increasing levels of time-detail,
-it is possible to subset the object by year, week, days - or even seconds.
-
-The {\em i} (row)
-argument to the subset operator ``{\tt [}'', in addition to accepting numeric
-values for indexing,
-can also be a character string, a time-based object, or a vector of either.
-The format must left-specified with respect to the standard ISO:8601
-time format --- {\em ``CCYY-MM-DD HH:MM:SS''}~\cite{ISO}. This means that for one
-to extract a particular month, it is necesssary to fully specify the
-year as well. To identify a particular hour, say all observations
-in the eighth hour on January 1, 2007, one would likewise need
-to include the full year, month and day - e.g. ``2007-01-01 08''.
-
-It is also possible to explicitly request a range of times via
-this index-based subsetting, using
-the ISO-recommended ``/'' as the range seperater.
-The basic form is {\em ``from/to''},
-where both {\em from} and {\em to}
-are optional. If either side is missing, it is interpretted as
-a request to retrieve data from the beginning, or through the end of the
-data object.
-
-Another benefit to this method is that exact starting and ending
-times need not match the underlying data - the nearest available
-observation will be returned that is within the requested time
-period.
-
-The following example shows how
-to extract the entire month of March 2007 - without having to
-manually identify the index positions or match the underlying
-index type. The results have been abbreviated to save space.
-<<xtsmethods, eval=FALSE>>=
-matrix_xts['2007-03']
-@
-<<xtsmethods-hidden, echo=FALSE>>=
-head(matrix_xts['2007-03'],5)
-cat('...\n')
-@
-
-Now extract all the data from the beginning through
-January 7, 2007.
-<<xtsmethods2, keep.source=TRUE, eval=FALSE>>=
-matrix_xts['/2007-01-07']
-@
-<<xtsmethods2-hidden, echo=FALSE>>=
-matrix_xts['/2007-01-07']
-@
-Additional xts tools providing subsetting are the
-{\tt first} and {\tt last} functions.
-In the spirit of head and tail from
-the {\em utils} recommended package, they allow
-for string based subsetting, without forcing
-the user to conform to the specifics of the
-time index, similar in usage to the {\em by}
-arguments of {\tt aggregate.zoo} and {\tt seq.POSIXt}.
-
-Here is the first 1 week of the data
-<<xtsfirstandlast, eval=FALSE>>=
-first(matrix_xts,'1 week')
-@
-<<xtsfirstandlast-hidden, echo=FALSE>>=
-head(first(matrix_xts,'1 week'))
-@
-
-...and here is the first 3 days of the
-last week of the data.
-<<xtsfirstandlast2>>=
-first(last(matrix_xts,'1 week'),'3 days')
-@
-\subsubsection*{Indexing}
-While the subsetting ability of the above makes
-exactly {\em which} time-based class you choose
-for your index a bit less relevant, it is none-the-less
-a factor that is beneficial to have control over.
-
-To that end, {\tt xts} provides facilities for indexing
-based on any of the current time-based classes. These
-include {\tt Date}, {\tt POSIXct}, {\tt chron}, {\tt yearmon},
-{\tt yearqtr}, and {\tt timeDate}. The index itself may
-be accessed via the zoo generics extended to xts --- {\tt index} and
-the replacement function {\tt index<-}.
-
-It is also possible to directly query and set the
-index class of an {\tt xts} object by using the respective functions
-{\tt indexClass} and {\tt indexClass<-}.
-Temporary conversion, resulting in a new object with the requested
-index class, can be accomplished via the {\tt convertIndex} function.
-
-<<indexClass>>=
-indexClass(matrix_xts)
-indexClass(convertIndex(matrix_xts,'POSIXct'))
-@
-\pagebreak
-\subsubsection*{Plotting}
-\SweaveOpts{height=5,width=10}
-%\setkeys{Gin}{width=0.8\textwidth}
-The use of time-based indexes within {\tt xts} allows
-for assumptions to be made regarding the x-axis
-of plots. The {\tt plot} method
-makes use of the {\tt xts} function {\tt axTicksByTime}, which
-heuristically identifies suitable tickmark locations
-for printing given a time-based object.
-
-When {\tt axTickByTime} is called with its
-{\tt ticks.on} argument set to ``auto'', the result
-is a vector of suitably chosen tickmark locations.
-One can also specify the specific points to use
-by passing a character string to the argument
-indicating which time period to create tickmarks on.
-<<xtsaxTicksByTime>>=
-axTicksByTime(matrix_xts, ticks.on='months')
-@
-A simple example of the plotting functionality
-offered by this labelling can be seen here:
-\begin{center}
-<<xtsplot, fig=TRUE>>=
-plot(matrix_xts[,1],major.ticks='months',minor.ticks=FALSE,main=NULL,col=3)
-@
-\end{center}
-
-\subsection{Restoring the original class - {\tt reclass} \& {\tt Reclass}}
-By now you may be interested in some of the xts functionality
-presented, and wondering how to incorporate it into
-a current workflow --- but not yet ready to commit
-to using it exclusively.
-
-If it is desirable to only use the subsetting tools
-for instance, a quick conversion to xts via {\tt as.xts}
-will allow full access to the above subsetting tools. When
-it is then necessary to continue your analysis using
-the original class, it is as simple as calling the
-function {\tt reclass} to return the object to its
-original class.
-
-\subsubsection*{(Re)converting classes manually: {\tt reclass}}
-<<asxtsreclass, keep.source=TRUE>>=
-# using xts-style subsetting doesn't work on non-xts objects
-sample_matrix['2007-06']
-# convert to xts to use time-based subsetting
-str(as.xts(sample_matrix)['2007-06'])
-
-# reclass to get to original class back
-str(reclass(as.xts(sample_matrix)['2007-06']))
-@
-
-This differs dramatically from the standard {\tt as.*****}
-conversion though. Internally, key attributes of your
-original data object are preserved and adjusted to
-assure that the process introduces no changes other
-than those requested. Think of it as a smart {\tt as}.
-
-Behind the scenes, {\tt reclass} has enormous value
-in functions that convert all incoming data to {\tt xts}
-for simplified processing. Often it is necessary to
-return an object back to the user in the class he
-is expecting --- following the principal of least surprise.
-It is in these circumstances where {\tt reclass} can
-turn hours of tedious development into mere minutes per function. More
-details on the details of using this functionality
-for developers will be covered in section \ref{developer},
-\textbf{Developing with xts}.
-
-A user friendly interface of this \emph{reclass} functionality, though
-implicit, is available in the {\tt Reclass} function.
-It's purpose is to make it easy to preserve an object's attributes after calling
-a function that is not programmed to be aware of your particular class.
-
-\pagebreak
-\subsubsection*{Letting xts handle the details: {\tt Reclass}}
-
-If the function you require does not make use of
-{\tt reclass} internally, it may still be possible to let
-xts convert and reconvert your time-based object for you.
-The caveat here is that the object returned:
-\begin{quote}
-\begin{itemize}
-\item must be of the same length as the first argument to
-the function.
-\item intended to be coerced back to the class of the first
-argument
-\end{itemize}
-\end{quote}
-Simply wrapping the function
-that meets these criteria in {\tt Reclass} will
-result in an
-attempt to coerce the returned output of the function
-
-<<usereclass, keep.source=TRUE>>=
-z <- zoo(1:10,Sys.Date()+1:10)
-# filter converts to a ts object - and loses the zoo class
-(zf <- filter(z, 0.2))
-class(zf)
-# using Reclass, the zoo class is preserved
-(zf <- Reclass(filter(z, 0.2)))
-class(zf)
-@
-
-The {\tt Reclass} function is still a bit experimental, and will
-certainly improve in time, but for now provides at least
-an alternative option to maintain your object's class
-and attributes when the function you require can't on its own.
-
-\subsection{Additional time-based tools}
-In addition to the core {\tt xts} tools covered
-above, there are more functions that are included
-in xts to make the process of dealing with
-time-series data easier. Some of these have been
-moved from the package {\tt quantmod} to {\tt xts}
-to make it easier to use them within other applications.
-
-\subsubsection*{Calculate periodicity}
-The {\tt periodicity} function provides
-a quick summary as to the underlying
-periodicity of most time-series like
-objects. Primarily a wrapper to {\tt difftime}
-it provides a quick and concise summary
-of your data.
-<<periodicity>>=
-periodicity(matrix_xts)
-@
-\subsubsection*{Find endpoints by time}
-Another common issue with time-series data
-is identifying the endpoints with respect to
-time. Often it is necessary to break data
-into hourly or monthly intervals to calculate
-some statistic. A simple call to {\tt endpoints}
-offers a quick vector of values suitable
-for subsetting a dataset by. Note that the first
-element it zero, which is used to delineate the \emph{end}.
-<<endpoints>>=
-endpoints(matrix_xts,on='months')
-endpoints(matrix_xts,on='weeks')
-@
-\subsubsection*{Change periodicity}
-One of the most ubiquitous type of data
-in finance is OHLC data (Open-High-Low-Close). Often is is necessary
-to change the periodicity of this data to something
-coarser - e.g. take daily data and aggregate to weekly
-or monthly. With {\tt to.period} and related wrapper
-functions it is a simple proposition.
-<<toperiod>>=
-to.period(matrix_xts,'months')
-periodicity(to.period(matrix_xts,'months'))
-
-# changing the index to something more appropriate
-to.monthly(matrix_xts)
-@
-The {\tt to.monthly} wrapper automatically requests that the
-returned object have an index/rownames using
-the {\tt yearmon} class. With the {\tt indexAt}
-argument it is possible to align most series
-returned to the end of the period, the beginning of the period,
-or the first or last observation of the period ---
-even converting to something like {\tt yearmon} is supported. The online
-documentation provides more details as to additional
-arguments.
-
-\subsubsection*{Periodically apply a function}
-Often it is desirable to be able to calculate a
-particular statistic, or evaluate a function, over
-a set of non-overlapping time periods. With the
-{\tt period.apply} family of functions
-it is quite simple.
-
-The following examples illustrate a
-simple application of the {\tt max} function
-to our example data.
-<<periodapply, keep.source=TRUE>>=
-# the general function, internally calls sapply
-period.apply(matrix_xts[,4],INDEX=endpoints(matrix_xts),FUN=max)
-@
-
-<<applymonthly, keep.source=TRUE>>=
-# same result as above, just a monthly interface
-apply.monthly(matrix_xts[,4],FUN=max)
-@
-
-<<periodsum, keep.source=TRUE>>=
-# using one of the optimized functions - about 4x faster
-period.max(matrix_xts[,4], endpoints(matrix_xts))
-@
-
-In addition to {\tt apply.monthly}, there are
-wrappers to other common time frames including:
-{\tt apply.daily}, {\tt apply.weekly}, {\tt apply.quarterly},
[TRUNCATED]
To get the complete diff run:
svnlook diff /svnroot/xts -r 787
More information about the Xts-commits
mailing list