Z's ordered observations

Z's ordered observations [R logo]

Help pages for package `zoo' version 1.2-2

A B C D E F H I L M N O P R S T V W X Y Z misc

-.yearmon | An Index Class for Monthly Data
-.yearqtr | An Index Class for Quarterly Data

-- A --

aggregate.zoo | Compute Summary Statistics of zoo Objects
as.character.yearmon | An Index Class for Monthly Data
as.character.yearqtr | An Index Class for Quarterly Data
as.data.frame.zoo | Coercion from and to zoo
as.Date.integer | Date Conversion Functions from Numeric, Integer and ts Objects
as.Date.numeric | Date Conversion Functions from Numeric, Integer and ts Objects
as.Date.ts | Date Conversion Functions from Numeric, Integer and ts Objects
as.Date.yearmon | An Index Class for Monthly Data
as.Date.yearqtr | An Index Class for Quarterly Data
as.list.ts | Coercion from and to zoo
as.list.zoo | Coercion from and to zoo
as.matrix.zoo | Coercion from and to zoo
as.numeric.yearmon | An Index Class for Monthly Data
as.numeric.yearqtr | An Index Class for Quarterly Data
as.POSIXct.yearmon | An Index Class for Monthly Data
as.POSIXct.yearqtr | An Index Class for Quarterly Data
as.POSIXlt.yearmon | An Index Class for Monthly Data
as.POSIXlt.yearqtr | An Index Class for Quarterly Data
as.ts.zoo | Coercion from and to zoo
as.ts.zooreg | Regular zoo Series
as.vector.zoo | Coercion from and to zoo
as.yearmon | An Index Class for Monthly Data
as.yearqtr | An Index Class for Quarterly Data
as.zoo | Coercion from and to zoo
as.zoo.factor | Z's Ordered Observations
as.zoo.irts | Coercion from and to zoo
as.zoo.its | Coercion from and to zoo
as.zoo.ts | Coercion from and to zoo
as.zoo.zoo | Coercion from and to zoo
as.zoo.zooreg | Regular zoo Series
as.zooreg | Regular zoo Series
Axis.yearmon | An Index Class for Monthly Data
axis.yearmon | An Index Class for Monthly Data
Axis.yearqtr | An Index Class for Quarterly Data
axis.yearqtr | An Index Class for Quarterly Data

-- B --

barplot.zoo Plotting zoo Objects

-- C --

c.yearmon | An Index Class for Monthly Data
c.yearqtr | An Index Class for Quarterly Data
c.zoo | Merge Two or More zoo Objects
cbind.zoo | Merge Two or More zoo Objects
coredata | Extracting/Replacing the Core Data of Objects
cummax.zoo | Z's Ordered Observations
cummin.zoo | Z's Ordered Observations
cumprod.zoo | Z's Ordered Observations
cumsum.zoo | Z's Ordered Observations
cycle.zoo | Regular zoo Series
cycle.zooreg | Regular zoo Series

-- D --

deltat.zoo | Regular zoo Series
deltat.zooreg | Regular zoo Series
diff.zoo | Lags and Differences of zoo Objects

-- E --

end.zoo Extracting/Replacing the Index of Objects

-- F --

format.yearmon | An Index Class for Monthly Data
format.yearqtr | An Index Class for Quarterly Data
frequency.zoo | Regular zoo Series
frequency.zooreg | Regular zoo Series

-- H --

head.ts | Z's Ordered Observations
head.zoo | Z's Ordered Observations

-- I --

index | Extracting/Replacing the Index of Objects
index2char | Z's Ordered Observations
is.regular | Check Regularity of a Series
is.zoo | Z's Ordered Observations

-- L --

lag.zoo | Lags and Differences of zoo Objects
lag.zooreg | Regular zoo Series
lines.zoo | Plotting zoo Objects

-- M --

make.par.list | Make a List from a Parameter Specification
MATCH | Value Matching
MATCH.yearmon | An Index Class for Monthly Data
MATCH.yearqtr | An Index Class for Quarterly Data
merge.zoo | Merge Two or More zoo Objects

-- N --

na.approx | Replace NA by Interpolation
na.contiguous | Z's Ordered Observations
na.locf | Last Observation Carried Forward
na.spline | Replace NA by Interpolation
na.trim | Trim Leading/Trailing Missing Observations

-- O --

Ops.yearmon | An Index Class for Monthly Data
Ops.yearqtr | An Index Class for Quarterly Data
Ops.zoo | Z's Ordered Observations
ORDER | Ordering Permutation

-- P --

panel.arrows.its | Plot zoo Series with Lattice
panel.arrows.ts | Plot zoo Series with Lattice
panel.arrows.zoo | Plot zoo Series with Lattice
panel.lines.its | Plot zoo Series with Lattice
panel.lines.ts | Plot zoo Series with Lattice
panel.lines.zoo | Plot zoo Series with Lattice
panel.plot.custom | Plot zoo Series with Lattice
panel.plot.default | Plot zoo Series with Lattice
panel.points.its | Plot zoo Series with Lattice
panel.points.ts | Plot zoo Series with Lattice
panel.points.zoo | Plot zoo Series with Lattice
panel.polygon.its | Plot zoo Series with Lattice
panel.polygon.ts | Plot zoo Series with Lattice
panel.polygon.zoo | Plot zoo Series with Lattice
panel.rect.its | Plot zoo Series with Lattice
panel.rect.ts | Plot zoo Series with Lattice
panel.rect.zoo | Plot zoo Series with Lattice
panel.segments.its | Plot zoo Series with Lattice
panel.segments.ts | Plot zoo Series with Lattice
panel.segments.zoo | Plot zoo Series with Lattice
panel.text.its | Plot zoo Series with Lattice
panel.text.ts | Plot zoo Series with Lattice
panel.text.zoo | Plot zoo Series with Lattice
plot.zoo | Plotting zoo Objects
points.zoo | Plotting zoo Objects
print.yearmon | An Index Class for Monthly Data
print.yearqtr | An Index Class for Quarterly Data
print.zoo | Z's Ordered Observations

-- R --

range.zoo | Z's Ordered Observations
rapply | Apply Rolling Functions
rapply-deprecated | Apply Rolling Functions
rbind.zoo | Merge Two or More zoo Objects
read.zoo | Read zoo Series via read.table
rollapply | Apply Rolling Functions
rollmax | Rolling Means/Maximums/Medians
rollmean | Rolling Means/Maximums/Medians
rollmedian | Rolling Means/Maximums/Medians

-- S --

scale.zoo | Z's Ordered Observations
start.zoo | Extracting/Replacing the Index of Objects
str.zoo | Z's Ordered Observations
summary.zoo | Z's Ordered Observations

-- T --

t.zoo | Z's Ordered Observations
tail.ts | Z's Ordered Observations
tail.zoo | Z's Ordered Observations
time.zoo | Extracting/Replacing the Index of Objects

-- V --

value Extracting/Replacing the Index of Objects

-- W --

window.zoo Extract/Replacing the Time Windows of Objects

-- X --

xyplot.its | Plot zoo Series with Lattice
xyplot.ts | Plot zoo Series with Lattice
xyplot.zoo | Plot zoo Series with Lattice

-- Y --

yearmon | An Index Class for Monthly Data
yearqtr | An Index Class for Quarterly Data

-- Z --

zoo | Z's Ordered Observations
zooreg | Regular zoo Series

-- misc --

[.yearmon | An Index Class for Monthly Data
[.yearqtr | An Index Class for Quarterly Data
[.zoo | Z's Ordered Observations


Compute Summary Statistics of zoo Objects

Description

Splits a "zoo" object into subsets along a coarser index grid, computes summary statistics for each, and returns the reduced "zoo" object.

Usage

## S3 method for class 'zoo':
aggregate(x, by, FUN, ...)

Arguments

x | an object of class "zoo".
by | index vector of the same length as index(x) which defines aggregation groups and the new index to be associated with each group. If by is a function, then it is applied to index(x) to obtain the aggregation groups.
FUN | a scalar function to compute the summary statistics which can be applied to all subsets.
... | further arguments passed to FUN.

Value

An object of class "zoo" or "zooreg" (if the resulting series is.regular).

See Also

zoo

Examples

## averaging over values in a month:
# long series
x.date <- as.Date(paste(2004, rep(1:4, 4:1), seq(1,20,2), sep = "-"))
x <- zoo(rnorm(12), x.date)
# coarser dates
x.date2 <- as.Date(paste(2004, rep(1:4, 4:1), 1, sep = "-"))
x2 <- aggregate(x, x.date2, mean)
# 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)

## aggregate on month and extend to monthly time series
if(require(chron)) {
y <- zoo(matrix(11:15,nr=5,nc=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
# replacing each such group with the first observation in that month.
# Uses fact that chron dates format, by default, to mm/dd/yy
firstofmonth <- function(x) chron(sub("/../", "/01/", format(x)))
y2 <- aggregate(y, firstofmonth(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)

# 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)
}
[Package zoo version 1.2-2 Index]


Date Conversion Functions from Numeric, Integer and ts Objects

as.Date.numeric(zoo) R Documentation

Date Conversion Functions from Numeric Integer and ts Objects

Description

Functions to convert numeric and related classes to objects of class "Date" representing calendar dates.

Usage

## S3 method for class 'numeric':
as.Date(x, ...)

## S3 method for class 'integer':
as.Date(x, ...)
## S3 method for class 'ts':
as.Date(x, offset = 0, ...)

Arguments

x | An object of class "numeric", "integer" or "ts" respectively.
offset | A value added to time(x).
... | Further arguments. Currently not used.

Details

The as.Date.integer method interprets the argument x as the number of days since the origin 1970-01-01 so that the origin corresponds to 0. Negative values are allowed.

The as.Date.numeric method like the as.Date.integer method applied to floor(x).

The as.Date.ts inspects time(x) and frequency(x): If the frequency is 1 or 4 or 12, time(x) is regarded to be annual, quarterly or monthly data respectively. If the frequency is something else, no coercion is done.

Value

The as.Date methods return an object of class "Date". In the case of as.Date.ts applied to a yearly, quarterly or monthly series the earliest date, i.e., first of year, quarter or month, is returned.

See Also

Date for details of the date class

Examples

as.Date(0) # origin, i.e. 1970-01-01

# all three result in origin and next 9 days
as.Date(0:9)
as.Date(0) + 0:9
myts <- ts(rnorm(10), start = 0)
as.Date(unclass(time(myts)))

# both result in ten firsts of year starting 2001-01-01
as.Date(ts(rnorm(10)), offset = 2000)
as.Date(ts(rnorm(10), start = 2001))

# both result in ten firsts of month starting with 1990-01-01
as.Date(ts(rnorm(10), start = c(90,1), freq = 12), offset = 1900)
as.Date(ts(rnorm(10), start = c(1990,1), freq = 12))


Coercion from and to zoo

Description

Methods for coercing "zoo" objects to other classes and a generic function as.zoo for coercing objects to class "zoo".

Usage

as.zoo(x, ...)

Arguments

x | an object,
... | further arguments passed to zoo when the return object is created.

Details

as.zoo currently has a default method and methods for ts, its and irts objects (and zoo objects themselves).

Methods for coercing objects of class "zoo" to other classes currently include: as.ts, as.matrix, as.vector, as.data.frame, as.list (the latter also being available for "ts" objects). Furthermore the coercion function as.its.zoo is provided, but works only if the corresponding package is attached.

In the conversion between zoo and ts, the zooreg class is always used.

Value

as.zoo returns a zoo object.

See Also

zoo, zooreg, ts, its, irts

Examples

## coercion to zoo:
## default method
as.zoo(rnorm(5))
## method for "ts" objects
as.zoo(ts(rnorm(5), start = 1981, freq = 12))

## 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)
as.vector(x)
as.data.frame(x)
as.list(x)


Extracting/Replacing the Core Data of Objects

Description

Generic functions for extracting the core data contained in a (more complex) object and replacing it.

Usage

coredata(x, ...)
coredata(x) <- value

Arguments

x | an object.
... | further arguments passed to methods.
value | a suitable value object for use with x.

Value

In zoo, there are currently coredata methods for time series objects of class "zoo", "ts", "its", "irts", all of which strip off the index/time attributes and return only the observations. The are also corresponding replacement methods for these classes.

See Also

zoo

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
## and only matrix of observations
coredata(x)

## change the observations
coredata(x) <- matrix(1:20, ncol = 2)
x


Replacing the Index of Objects

Description

Generic function for replacing the frequency of an object.

Usage

frequency(x) <- value

Arguments

x | an object.
value | a frequency.

Details

frequency<- is a generic function for replacing (or assigning) the frequency of an object. Currently, there is a "zooreg" and a "zoo" method. In both cases, the value is assigned to the "frequency" of the object if it complies with the index(x).

See Also

zooreg, index

Examples

z <- zooreg(1:5)
z
as.ts(z)
frequency(z) <- 3
z
as.ts(z)


Extracting/Replacing the Index of Objects

Description

Generic functions for extracting the index of an object and replacing it.

Usage

index(x, ...)
index(x) <- value

Arguments

x | an object.
... | further arguments passed to methods.
value | an ordered vector of the same length as the "index" attribute of x.

Details

index is a generic function for extracting the index of objects, currently it has a default method and a method for zoo objects which is the same as the time method for zoo objects. Another pair of generic functions provides replacing the index or time attribute. Methods are available for "zoo" objects only, see examples below.

The start and end of the index/time can be queried by using the methods of start and end.

See Also

time, zoo

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)
time(x)

## change class of index from Date to POSIXct
## relative to current time zone
x
index(x) <- as.POSIXct(format(time(x)),tz="")
x

## replace index/time of a zoo object
index(x) <- 1:5
x
time(x) <- 6:10
x

## query start and end of a zoo object
start(x)
end(x)

## query index of a usual matrix
xm <- matrix(rnorm(10), ncol = 2)
index(xm)


Check Regularity of a Series

Description

is.regular is a regular function for checking whether a series of ordered observations has an underlying regularity or is even strictly regular.

Usage

is.regular(x, strict = FALSE)

Arguments

x | an object (representing a series of ordered observations).
strict | logical. Should strict regularity be checked? See details.

Details

A time series can either be irregular (unequally spaced), strictly regular (equally spaced) or have an underlying regularity, i.e., be created from a regular series by omitting some observations. Here, the latter property is called regular. Consequently, regularity follows from strict regularity but not vice versa.

is.regular is a generic function for checking regularity (default) or strict regularity. Currently, it has methods for "ts" objects (which are always strictly regular), "zooreg" objects (which are at least regular), "zoo" objects (which can be either irregular, regular or even strictly regular) and a default method. The latter coerces x to "zoo" before checking its regularity.

Value

A logical is returned indicating whether x is (strictly) regular.

See Also

zooreg, zoo

Examples

## checking of a strictly regular zoo series
z <- zoo(1:10, seq(2000, 2002.25, by = 0.25), frequency = 4)
z
class(z)
frequency(z) ## extraction of frequency attribute
is.regular(z)
is.regular(z, strict = TRUE)
## by omitting observations, the series is not strictly regular
is.regular(z[-3])
is.regular(z[-3], strict = TRUE)

## 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
class(z)
frequency(z) ## data driven computation of frequency
is.regular(z)
is.regular(z, strict = TRUE)
## by omitting observations, the series is not strictly regular
is.regular(z[-3])
is.regular(z[-3], strict = TRUE)

## checking of an irregular zoo series
z <- zoo(1:10, rnorm(10))
z
class(z)
frequency(z) ## attempt of data-driven frequency computation
is.regular(z)
is.regular(z, strict = TRUE)


Lags and Differences of zoo Objects

Description

Methods for computing lags and differences of "zoo" objects.

Usage

## S3 method for class 'zoo':
lag(x, k = 1, na.pad = FALSE, ...)
## S3 method for class 'zoo':
diff(x, lag = 1, differences = 1, arithmetic = TRUE, na.pad = FALSE, ...)

Arguments

x | a "zoo" object.
k, lag | the number of lags (in units of observations). Note the sign of k behaves as in lag.
differences | an integer indicating the order of the difference.
arithmetic | logical. Should arithmetic (or geometric) differences be computed?
na.pad | logical. If TRUE it adds any times that would not otherwise have been in the result with a value of NA. If FALSE those times are dropped.
... | currently not used.

Details

These methods for "zoo" objects behave analogously to the default methods. The only additional arguments are arithmetic in diff na.pad in lag.zoo which can also be specified in diff.zoo as part of the dots. Also, "k" can be a vector of lags in which case the names of "k", if any, are used in naming the result.

Value

The lagged or differenced "zoo" object.

Note

Note the sign of k: a series lagged by a positive k is shifted earlier in time.

See Also

zoo, lag, diff

Examples

x <- zoo(11:21)

lag(x, k = 1)
lag(x, k = -1)
# this pairs each value of x with the next or future value
merge(x, lag1 = lag(x, k=1))
diff(x^2)
diff(x^2, na.pad = TRUE)


Make a List from a Parameter Specification

Description

Process parameters so that a list of parameter specifications is returned (used by plot.zoo and xyplot.zoo).

Usage

make.par.list(nams, x, n, m, def, recycle = sum(unnamed) > 0)

Arguments

nams | character vector with names of variables.
x | list or vector of parameter specifications, see details.
n | numeric, number of rows.
m | numeric, number of columns. (Only determines whether m is 1 or greater than 1.
def | default parameter value.
recycle | logical. If TRUE recycle columns to provide unspecified ones. If FALSE use def to provide unspecified ones. This only applies to entire columns. Within columns recycling is always done regardless of how recycle is set. Defaults to TRUE if there is at least one unnamed variable and defaults to FALSE if there are only named variables in x.

Details

This function is currently intended for internal use. It is currently used by plot.zoo and xyplot.zoo but might also be used in the future to create additional new plotting routines. It creates a new list which uses the named variables from x and then assigns the unnamed in order. For the remaining variables assign them the default value if !recycle or recycle the unnamed variables if recycle.

Value

A list of parameters, see details.

Examples

make.par.list(letters[1:5], 1:5, 3, 5)
suppressWarnings( make.par.list(letters[1:5], 1:4, 3, 5, 99) )
make.par.list(letters[1:5], c(d=3), 3, 5, 99)
make.par.list(letters[1:5], list(d=1:2, 99), 3, 5)
make.par.list(letters[1:5], list(d=1:2, 99, 100), 3, 5)


Value Matching

Description

MATCH is a generic function for value matching.

Usage

MATCH(x, table, nomatch = NA, ...)

Arguments

x | an object.
table | the values to be matched against.
nomatch | the value to be returned in the case when no match is found. Note that it is coerced to integer.
... | further arguments to be passed to methods.

Details

MATCH is a new generic function which aims at providing the functionality of the non-generic base function match for arbitrary objects. Currently, there is only a default method which simply calls match.

See Also

match

Examples

MATCH(1:5, 2:3)


Merge Two or More zoo Objects

Description

Merge two zoo objects by common indexes (times), or do other versions of database join operations.

Usage

## S3 method for class 'zoo':
merge(..., all = TRUE, fill = NA, suffixes = NULL,
  retclass = c("zoo", "list", "data.frame"))

Arguments

... | two or more objects, usually of class "zoo".
all | logical vector having the same length as the number of "zoo" objects to be merged (otherwise expanded).
fill | an element for filling gaps in merged "zoo" objects (if any).
suffixes | character vector of the same length as the number of "zoo" objects specifying the suffixes to be used for making the merged column names unique.
retclass | character that specifies the class of the returned result. It can be "zoo" (the default), "list" or NULL. For details see below.

Details

The merge method for "zoo" objects combines the columns of several objects along the union of the dates for all = TRUE, the default, or the intersection of their dates for all = FALSE filling up the created gaps (if any) with the fill pattern.

The first argument must be a zoo object. If any of the remaining arguments are plain vectors or matrices with the same length or number of rows as the first argument then such arguments are coerced to "zoo" using as.zoo. If they are plain but have length 1 then they are merged after all non-scalars such that their column is filled with the value of the scalar.

all can be a vector of the same length as the number of "zoo" objects to merged (if not, it is expanded): All indexes (times) of the objects corresponding to TRUE are included, for those corresponding to FALSE only the indexes present in all objects are included. This allows intersection, union and left and right joins to be expressed.

If retclass is "zoo" (the default) a single merged "zoo" object is returned. If it is set to "list" a list of "zoo objects is returned. If retclass = NULL then instead of returning a value it updates each argument (if it is a variable rather than an expression) in place so as to extend or reduce it to use the common index vector.

The indexes of different "zoo" objects can be of different classes and are coerced to one class in the resulting object (with a warning).

The default cbind method is essentially the default merge method, but does not support the retclass argument. The rbind method combines the dates of the "zoo" objects (duplicate dates are not allowed) and combines the rows of the objects. Furthermore, the c method is identical to the rbind method.

Value

An object of class "zoo" if retclass="zoo", an object of class "list" if retclass="list" or modified arguments as explained above if retclass=NULL. If the result is an object of class "zoo" then its frequency is the common frequency of its zoo arguments, if they have a common frequency.

See Also

zoo

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)
merge(y1, y2, all = FALSE, suffixes = c("a", "b"))
merge(y1, y2, all = TRUE)
merge(y1, y2, all = TRUE, fill = 0)

## 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)

## 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)
# same but with zero fill
merge(z, z0, fill = 0)

merge(z, coredata(z),  1)


Replace NA by Interpolation

Description

Generic functions for replacing each NA with interpolated values.

Usage

na.approx(object, ...)
## Default S3 method:
na.approx(object, along = index(object), na.rm = TRUE, ...)

na.spline(object, ...)
## Default S3 method:
na.spline(object, along = index(object), na.rm = TRUE, ...)

Arguments

object | object in which NAs are to be replaced
along | variable to use for interpolation. Has to be numeric, is otherwise coerced to numeric.
na.rm | logical. Should leading NAs be removed?
... | further arguments passed to methods.

Details

Missing values (NAs) are replaced by linear interpolation via approx or cubic spline interpolation via spline, respectively.

By default the index associated with object is used for interpolation. Note, that if this calls index.default this gives an equidistant spacing 1:NROW(object). If object is a matrix or data.frame, the interpolation is done separately for each column.

Value

An object in which each NA in the input object is replaced by interpolating the non-NA values before and after it. Leading NAs are omitted (if na.rm = TRUE) or not replaced (if na.rm = FALSE).

See Also

zoo, approx, spline, stinterp

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)
## use equidistant spacing
na.approx(z, 1:6)

na.approx(zoo(c(NA,9,3,2,3,2)))


Last Observation Carried Forward

Description

Generic function for replacing each NA with the most recent non-NA prior to it.

Usage

na.locf(object, na.rm = TRUE, ...)
## Default S3 method:
na.locf(object, na.rm = TRUE, rev = FALSE, ...)

Arguments

object | an object.
na.rm | logical. Should leading NAs be removed?
rev | logical. Should the observations be reversed before applying LOCF? This corresponds to NOCB (next observation carried backward).
... | further arguments passed to methods.

Value

An object in which each NA in the input object is replaced by the most recent non-NA prior to it. If there are no earlier non-NAs then the NA is omitted (if na.rm = TRUE) or it is not replaced (if na.rm = FALSE).

See Also

zoo

Examples

az <- zoo(1:6)

bz <- zoo(c(2,NA,1,4,5,2))
na.locf(bz)
na.locf(bz, rev = TRUE)

cz <- zoo(c(NA,9,3,2,3,2))
na.locf(cz)


Trim Leading/Trailing Missing Observations

Description

Generic function for removing leading and trailing NAs.

Usage

na.trim(object, ...)
## Default S3 method:
na.trim(object, sides = c("both", "left", "right"), ...)

Arguments

object | an object.
sides | character specifying whether NAs are to be removed from both sides, just from the left side or just from the right side.
... | further arguments passed to methods.

Value

An object in which leading and/or trailing NAs have been removed.

See Also

na.omit, zoo

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)
na.trim(xx)

# 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))


Ordering Permutation

Description

ORDER is a generic function for computing ordering permutations.

Usage

ORDER(x, ...)
## Default S3 method:
ORDER(x, ..., na.last = TRUE, decreasing = FALSE)

Arguments

x | an object.
... | further arguments to be passed to methods.
na.last | for controlling the treatment of NAs. If TRUE, missing values in the data are put last; if FALSE, they are put first; if NA, they are removed.
decreasing | logical. Should the sort order be increasing or decreasing?

Details

ORDER is a new generic function which aims at providing the functionality of the non-generic base function order for arbitrary objects. Currently, there is only a default method which simply calls order.

See Also

order

Examples

ORDER(rnorm(5))


Plotting zoo Objects

Description

Plotting method for objects of class "zoo".

Usage

## S3 method for class 'zoo':
plot(x, y = NULL, screens = 1, plot.type = c("multiple", "single"),
  panel = lines, xlab = "Index", ylab = NULL, main = NULL,
  xlim = NULL, ylim = NULL, xy.labels = FALSE, xy.lines = NULL,
  oma = c(6, 0, 5, 0), mar = c(0, 5.1, 0, 2.1),
  col = 1, lty = 1, pch = 1, type = "l", nc, widths = 1, heights = 1, ...)
## S3 method for class 'zoo':
lines(x, y = NULL, type = "l", ...)
## S3 method for class 'zoo':
points(x, y = NULL, type = "p", ...)

Arguments

x | an object of class "zoo".
y | an object of class "zoo". If y is NULL (the default) a time series plot of x is produced, otherwise if both x and y are univariate "zoo" series, a scatter plot of y versus x is produced.
screens | factor (or coerced to factor) whose levels specify which graph each series is to be plotted in. screens=c(1,2,1) would plot series 1, 2 and 3 in graphs 1, 2 and 1.
plot.type | for multivariate zoo objects, "multiple" plots the series on multiple plots and "single" superimposes them on a single plot
panel | a function(x, y, col, lty, ...) which gives the action to be carried out in each panel of the display for plot.type = "multiple".
ylim | if plot.type = "multiple" then it can be a list of y axis limits. If not a list each graph has the same limits. If any list element is not a pair then its range is used instead. If plot.type = "single" then it is as in plot.
xy.labels | logical, indicating if text labels should be used in the scatter plot, or character, supplying a vector of labels to be used.
xy.lines | logical, indicating if lines should be drawn in the scatter plot. Defaults to the value of xy.labels if that is logical, otherwise to FALSE.
xlab, ylab, main, xlim, oma, mar | graphical arguments, see par.
col, lty, pch, type | graphical arguments that can be vectors or (named) lists. See the details for more information.
nc | the number of columns to use when plot.type = "multiple". Defaults to 1 for up to 4 series, otherwise to 2.
widths, heights | widths and heights for individual graphs, see layout.
... | additional graphical arguments.

Details

The methods for plot and lines are very similar to the corresponding ts methods. However, the handling of several graphical parameters is more flexible for multivariate series. These parameters can be vectors of the same length as the number of series plotted or are recycled if shorter. They can also be (partially) named list, e.g., list(A = c(1,2), c(3,4)) in which c(3, 4) is the default value and c(1, 2) the value only for series A. The screens argument can be specified in a similar way. If plot.type and screens conflict then multiple plots will be assumed. Also see the examples.

In addition to classical time series line plots, there is also a simple barplot method for "zoo" series.

See Also

zoo, plot.ts, barplot

Examples

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, plot.type = "single", 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)
par(usr = c(par("usr")[1:2], range(x2)))
lines(x2, lty = 2)
axis(4)

## 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)

## barplot
x <- zoo(cbind(rpois(5, 2), rpois(5, 3)), x.Date)
barplot(x, beside = TRUE)


Read zoo Series via read.table

Description

read.zoo is a convenience function for reading "zoo" series from text files.

Usage

read.zoo(file, format = "", tz = "", FUN = NULL, regular = FALSE, ...)

Arguments

file | character giving the name of the file which the data are to be read from. See read.table for more information.
format | date format argument passed to as.Date.character.
tz | time zone argument passed to as.POSIXct.
FUN | a function for computing the index from the first column of the data. See details.
regular | logical. Should the series be coerced to class "zooreg" (if the series is regular)?
... | further arguments passed to read.table.

Details

read.zoo is a convenience function which should make it easier to read data from a text file and turn it into a "zoo" series immediately. read.zoo reads the data file via read.table(file, ...). The first column of the resulting data is interpreted to be the index, the remaining columns the corresponding data. (If the file only has only column then that is assumed to be the data column and 1, 2, ... are used for the index.) To assign the appropriate class to the index, FUN can be specified and is applied to the first column. By default, read.zoo uses as.Date(as.character(x), format = format) if format is specified and as.POSIXct(as.character(x), tz = tz) if tz is specified; otherwise it tries to guess between "numeric", "Date" and "POSIXct".

If regular is set to TRUE and the resulting series has an underlying regularity, it is coerced to a "zooreg" series.

Value

An object of class "zoo" (or "zooreg").

See Also

zoo

Examples

## Not run:
## turn *numeric* first column into yearmon index
z <- read.zoo("foo.csv", sep = ",", FUN = as.yearmon)

## turn *character* first column into Date index
z <- read.zoo("foo.tab", format = "%m/%d/%Y")
## End(Not run)


Apply Rolling Functions

Description

A generic function for applying a function to rolling margins of an array.

Usage

rollapply(data, width, FUN, ..., by = 1, ascending = TRUE, by.column = TRUE,
 na.pad = FALSE, align = c("center", "left", "right"))

Arguments

data | the data to be used (representing a series of observations).
width | number of points per group.
FUN | the function to be applied. In the case of functions like +, %*%, etc., the function name must be quoted.
... | optional arguments to FUN.
by | calculate FUN for trailing width points at every by-th time point.
ascending | logical. If TRUE then points are passed to FUN in ascending order of time; otherwise, they are passed in descending order.
by.column | logical. If TRUE, FUN is applied to each column separately.
na.pad | logical. If TRUE then additional elements or rows of NAs are added so that result has same number of elements or rows as data.
align | character specifying whether result should be left- or right-aligned or centered (default).

Details

Groups time points in successive sets of width time points and applies FUN to the corresponding values. If FUN is mean, max or median and by.column is TRUE and there are no extra arguments then special purpose code is used to enhance performance. See rollmean, rollmax and rollmedian for more details.

Currently, there are methods for "zoo" and "ts" series.

In previous versions, this function was called rapply. It was renamed because from R 2.4.0 on, base R provides a different function rapply for recursive (and not rolling) application of functions. The function zoo::rapply is still provided for backward compatibility, however it dispatches now to rollapply methods.

Value

A object of the same class as data with the results of the rolling function.

See Also

rollmean

Examples

z <- zoo(11:15, as.Date(31:35))
rollapply(z, 2, mean)

z2 <- zoo(rnorm(6))
rollapply(z2, 3, mean, by = 3) # means of nonoverlapping groups of 3
aggregate(z2, c(3,3,3,6,6,6), mean) # same

rollapply(z2, 3, mean) # uses rollmean which is optimized for mean
rollmean(z2, 3) # same
rollapply(z2, 3, (mean)) # does not use rollmean


Rolling Means/Maximums/Medians

Description

Generic functions for computing rolling means, maximums and medians of ordered observations.

Usage

rollmean(x, k, na.pad = FALSE, align = c("center", "left", "right"), ...)
rollmax(x, k, na.pad = FALSE, align = c("center", "left", "right"), ...)
rollmedian(x, k, na.pad = FALSE, align = c("center", "left", "right"), ...)

Arguments

x | an object (representing a series of observations).
k | integer width of the rolling window. Must be odd for rollmedian.
na.pad | logical. Should NA padding be added at beginning?
align | character specifying whether result should be left- or right-aligned or centered (default).
... | Further arguments passed to methods.

Details

These functions compute rolling means, maximums and medians respectively and are thus similar to rollapply but are optimized for speed.

Currently, there are methods for "zoo" and "ts" series and default methods (intended for vectors). The default method of rollmedian is an interface to runmed. The default method of rollmean does not handle inputs that contain NAs. In such cases, use rollapply instead.

Value

An object of the same class as x with the rolling mean/max/median.

See Also

rollapply, zoo

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)
rollmax(x, 3)
rollmedian(x, 3)

xm <- zoo(matrix(1:12, 4, 3), x.Date[1:4])
rollmean(xm, 3)
rollmax(xm, 3)
rollmedian(xm, 3)

rollapply(xm, 3, mean) # uses rollmean
rollapply(xm, 3, function(x) mean(x)) # does not use rollmean


Extract/Replacing the Time Windows of Objects

Description

Methods for extracting time windows of "zoo" objects and replacing it.

Usage

## S3 method for class 'zoo':
window(x, index = index.zoo(x), start = NULL, end = NULL, ...)
## S3 method for class 'zoo':
window(x, index = index.zoo(x), start = NULL, end = NULL, ...) <- value

Arguments

x | an object.
index | the index/time window which should be extracted.
start | an index/time value. Only the indexes in index which are greater or equal to start are used.
end | an index/time value. Only the indexes in index which are lower or equal to end are used.
value | a suitable value object for use with window(x).
... | currently not used.

Value

Either the time window of the object is extracted (and hence return a "zoo" object) or it is replaced.

See Also

zoo

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

window(x, start = as.Date("2003-02-01"), end = as.Date("2003-03-01"))
window(x, index = x.date[1:6], start = as.Date("2003-02-01"))
window(x, index = x.date[c(4, 8, 10)])
window(x, index = x.date[c(4, 8, 10)]) <- matrix(1:6, ncol = 2)
x

## zooreg example (with plain numeric index)
z <- zooreg(rnorm(10), start = 2000, freq = 4)
window(z, start = 2001.75)
window(z, start = c(2001, 4))


Plot zoo Series with Lattice

Description

xyplot methods for time series objects (of class "zoo" or "ts", "its"). These functions are still under development and the interface and functionality might be modified/extended in future releases.

Usage

## S3 method for class 'zoo':
xyplot(x, data, screens = seq(length = NCOL(x)),
    default.scales = list(y = list(relation = "free")),
    layout = NULL, xlab = "Index", ylab = NULL,
    lty = trellis.par.get("plot.line")$lty,
    lwd = trellis.par.get("plot.line")$lwd,
    pch = trellis.par.get("plot.symbol")$pch,
    type = "l",
    col = trellis.par.get("plot.line")$col,
    strip = TRUE, panel = panel.plot.default, ...)

panel.plot.default(x, y, subscripts, groups,
    panel = panel.xyplot,
    col = 1, type = "p", pch = 20, lty = 1, lwd = 1, ...)

panel.plot.custom(...)

panel.lines.zoo(x, ...)
panel.points.zoo(x, ...)
panel.segments.zoo(x0, x1, ...)
panel.text.zoo(x, ...)
panel.rect.zoo(x0, x1, ...)
panel.arrows.zoo(x0, x1, ...)
panel.polygon.zoo(x, ...)

Arguments

x, x0, x1 | time series object of class "zoo", "ts" or "its". For panel.plot.default it should be a numeric vector.
y | numeric vector or matrix.
subscripts, groups, panel | arguments for panel functions, see description of panel argument in xyplot.
data | currently not used.
screens | factor (or coerced to factor) whose levels specify which graph each series is to be plotted in. screens = c(1, 2, 1) would plot series 1, 2 and 3 in graphs 1, 2 and 1.
default.scales | scales specification. The default is set so that all series have the "same" X axis but "free" Y axis. See xyplot in the lattice package for more information on scales. For users, it is recommended to set the scales argument instead of default.scales.
layout | numeric vector of length 2 specifying number of columns and rows in the plot, see xyplot for more details. The default is to fill columns with up to 5 rows.
xlab | character string used as the X axis label.
ylab | character string used as the Y axis label. If there are multiple panels it may be a character vector the same length as the number of panels.
lty, lwd, pch, type, col | graphical arguments passed to xyplot. These arguments can also be vectors or (named) lists, see details for more information.
strip | logical, character or function specifying headings used for panels. If character, should be a vector the same length as the number of panels. If TRUE column names are used for headers. If FALSE, no headings are produced. See xyplot for the case in which strip is a function.
... | additional arguments passed to xyplot.

Details

xyplot.zoo plots a "zoo", "ts" or "its" object using xyplot from lattice. Series of other classes are coerced to "zoo" first.

The handling of several graphical parameters is more flexible for multivariate series. These parameters can be vectors of the same length as the number of series plotted or are recycled if shorter. They can also be (partially) named list, e.g., list(A = c(1,2), c(3,4)) in which c(3, 4) is the default value and c(1, 2) the value only for series A. The screens argument can be specified in a similar way.

plot.panel.default is the default panel function. plot.panel.custom facilitates the development of custom panels. Usually it has one argument "panel" which specifies the custom panel. That panel typically calls plot.panel.default and uses the panel.number argument to take additional special action for particular panels. See the examples.

Value

Invisibly returns a "trellis" class object. Printing this object using print will display it.

Examples

library("lattice")
library("grid")

# 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)))

set.seed(1)
z <- zoo(cbind(a = 1:5, b = 11:15, c = 21:25) + rnorm(5))

# plot a blue running mean on the panel of b.
# Also add a grid.
# We show two ways to do it.

# Number 1.  Using trellis.focus.
print(xyplot(z))
trellis.focus("panel", 1, 2, highlight = FALSE)
z.mean <- rollmean(z, 3)
# uncomment next line and remove line after that when
# lattice makes panel.lines generic
# print(panel.lines(time(z.mean), z.mean[,2], col = "blue"))
print(panel.lines.zoo(z.mean[,2], col = "blue"))
print(panel.grid(h = 10, v = 10, col = "grey", lty = 3))
trellis.unfocus()

# Number 2. Using a custom panel routine.
## Not run:
# This example relies on R version 2.3.1.
# In R version 2.4.0, remove panel.number argument
# and use panel.number() function.
p <- function(x, y, groups = NULL, ..., panel.number) {
  panel.xyplot(x, y, groups = groups, ..., panel.number)
  if (panel.number == 2) {
    panel.lines.zoo(rollmean(zoo(y, x), 3), col = "blue")
    panel.grid(h = 10, v = 10, col = "grey", lty = 3)
  }
}
print(xyplot(z, panel = panel.plot.custom(panel = p)))
## End(Not run)

# 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.plot.default", trellis.panelArgs())
trellis.unfocus()

# same but make first (i.e. bottom) panel twice as large as others
print(xyplot(z), heights = list(c(2,1,1), units = "null"))
# add a grid - this method does not confine grid to frames
# To do that see prior example.
panel.grid()

# Plot all in one panel.
print(xyplot(z, screens = 1))

# 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 (upper) panel 3x the height of the 1st (lower) panel
# Also make the strip background orange.
p <- xyplot(z, screens = c(1,1,2), type = c("p", "l", "o"), col = 1:3,
  par.setting = 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")
z <- zoo(seq(length(Days))^2, Days)
Months <- Days[format(Days, "%d") == "01"]
Weeks <- Days[format(Days, "%w") == "0"]
xyplot(z, 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)


An Index Class for Monthly Data

Description

"yearmon" is a class for representing monthly data.

Usage

yearmon(x)

Arguments

x numeric (interpreted as being “in years”).

Details

The yearmon class is used to represent monthly data. Internally it holds the data as year plus 0 for January, 1/12 for February, 2/12 for March and so on in order that its internal representation is the same as ts class with frequency = 12. If x is not in this format it is rounded via floor(12*x + .0001)/12.

There are coercion methods available for various classes including: default coercion to "yearmon" (which coerces to "numeric" first) and coercion from "yearmon" to "Date" (see below), "POSIXct", "POSIXlt", "numeric", "character".

Value

Returns its argument converted to class yearmon.

See Also

yearqtr, zoo, zooreg, ts

Examples

x <- yearmon(2000 + seq(0, 23)/12)
x

# returned Date is the fraction of the way through
# the period given by frac (= 0 by default)
as.Date(x)
as.Date(x, frac = 1)
as.POSIXct(x)

z <- zoo(rnorm(24), x, frequency = 12)
z
as.ts(z)


An Index Class for Quarterly Data

Description

"yearqtr" is a class for representing quarterly data.

Usage

yearqtr(x)

Arguments

x numeric (interpreted as being “in years”).

Details

The yearqtr class is used to represent quarterly data. Internally it holds the data as year plus 0 for Quarter 1, 1/4 for Quarter 2 and so on in order that its internal representation is the same as ts class with frequency = 4. If x is not in this format it is rounded via floor(4*x + .0001)/4.

There are coercion methods available for various classes including: default coercion to "yearqtr" (which coerces to "numeric" first) and coercion from "yearqtr" to "Date" (see below), "POSIXct", "POSIXlt", "numeric", "character".

Value

Returns its argument converted to class yearqtr.

See Also

yearmon, zoo, zooreg, ts

Examples

x <- yearqtr(2000 + seq(0, 7)/4)
x

# returned Date is the fraction of the way through
# the period given by frac (= 0 by default)
as.Date(x)
as.Date(x, frac = 1)
as.POSIXct(x)

z <- zoo(rnorm(8), x, frequency = 4)
z
as.ts(z)


Z's Ordered Observations

Description

zoo is the creator for an S3 class of indexed totally ordered observations which includes irregular time series.

Usage

zoo(x, order.by = index(x), frequency = NULL)
## S3 method for class 'zoo':
print(x, style = , quote = FALSE, ...)

Arguments

x | a numeric vector, matrix or a factor.
order.by | an index vector with unique entries by which the observations in x are ordered. See the details for support of non-unique indexes.
frequency | numeric indicating frequency of order.by. If specified, it is checked whether order.by and frequency comply. If so, a regular "zoo" series is returned, i.e., an object of class c("zooreg", "zoo"). See below and zooreg for more details.
style | a string specifying the printing style which can be "horizontal" (the default for vectors), "vertical" (the default for matrices) or "plain" (which first prints the data and then the index).
quote | logical. Should characters be quoted?
... | further arguments passed to the print methods of the data and the index.

Details

zoo provides infrastructure for ordered observations which are stored internally in a vector or matrix with an index attribute (of arbitrary class, see below). The index must have the same length as NROW(x) except in the case of a zero length numeric vector in which case the index length can be any length. Emphasis has been given to make all methods independent of the index/time class (given in order.by). In principle, the data x could also be arbitrary, but currently there is only support for vectors and matrices and partial support for factors.

zoo is particularly aimed at irregular time series of numeric vectors/matrices, but it also supports regular time series (i.e., series with a certain frequency). zoo's key design goals are independence of a particular index/date/time class and consistency with ts and base R by providing methods to standard generics. Therefore, standard functions can be used to work with "zoo" objects and memorization of new commands is reduced.

When creating a "zoo" object with the function zoo, the vector of indexes order.by can be of (a single) arbitrary class (if x is shorter or longer than order.by it is expanded accordingly), but it is essential that ORDER(order.by) works. For other functions it is assumed that c(), length(), MATCH() and subsetting [, work. If this is not the case for a particular index/date/time class, then methods for these generic functions should be created by the user. Note, that to achieve this, new generic functions ORDER and MATCH are created in the zoo package with default methods corresponding to the non-generic base functions order and match. Furthermore, for certain (but not for all) operations the index class should have an as.numeric method (in particular for regular series) and an as.character method might improve printed output (see also below).

The index observations order.by should typically be unique, such that the observations can be totally ordered. Nevertheless, zoo() is able to create "zoo" objects with duplicated indexes and simple methods such as plot() or summary() or will typically work for such objects. However, this is not formally supported as the bulk of functionality provided in zoo requires unique index observations/time stamps. See below for an example how to remove duplicated indexes.

If a frequency is specified when creating a series via zoo, the object returned is actually of class "zooreg" which inherits from "zoo". This is a subclass of "zoo" which relies on having a "zoo" series with an additional "frequency" attribute (which has to comply with the index of that series). Regular "zooreg" series can also be created by zooreg, the zoo analogue of ts. See the respective help page and is.regular for further details.

Methods to standard generics for "zoo" objects currently include: print (see above), summary, str, head, tail, [ (subsetting), rbind, cbind, merge (see merge.zoo), aggregate (see aggregate.zoo), barplot, plot and lines (see plot.zoo).

To “prettify” printed output of "zoo" series the generic function index2char is used for turning index values into character values. It defaults to using as.character but can be customized if a different printed display should be used (although this should not be necessary, usually).

The subsetting method [ work essentially like the corresponding functions for vectors or matrices respectively, i.e., takes indexes of type "numeric", "integer" or "logical". But additionally, it can be used to index with observations from the index class of the series. If the index class of the series is one of the three classes above, the corresponding index has to be encapsulated in I() to enforce usage of the index class (see examples). Subscripting by a zoo object whose data contains logical values is undefined.

Additionally, zoo provides several generic functions and methods to work (a) on the data contained in a "zoo" object, (b) the index (or time) attribute associated to it, and (c) on both data and index:

(a) The data contained in "zoo" objects can be extracted by coredata (strips off all "zoo"-specific attributes) and modified using coredata<-. Both are new generic functions with methods for "zoo" objects, see coredata.

(b) The index associated with a "zoo" object can be extracted by index and modified by index<-. As the interpretation of the index as “time” in time series applications is more natural, there are also synonymous methods time and time<-. The start and the end of the index/time vector can be queried by start and end. See index.

(c) To work on both data and index/time, zoo provides methods lag, diff (see lag.zoo) and window, window<- (see window.zoo).

In addition to standard group generic function (see Ops), the following mathematical operations are availabe as methods for "zoo" objects: transpose t which coerces to a matrix first, and cumsum, cumprod, cummin, cummax which are applied column wise.

Coercion to and from "zoo" objects is available for objects of various classes, in particular "ts", "irts" and "its" objects can be coerced to "zoo", the reverse is available for "its" and for "irts" (the latter in package tseries). Furthermore, "zoo" objects can be coerced to vectors, matrices and lists and data frames (dropping the index/time attribute). See as.zoo.

Four methods are available for NA handling in the data of "zoo" objects: na.omit which returns a "zoo" object with incomplete observations removed, na.locf which replaces NAs by the last previous non-NA, na.contiguous which extracts the longest consecutive stretch of non-missing values in a "zoo" object and na.approx which uses linear interpolation to fill in NA values.

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 generic function rollapply provides this functionality for arbitrary functions and more efficient versions rollmean, rollmax, rollmedian are available for the mean, maximum and median respectively.

Value

A vector or matrix with an "index" attribute of the same dimension (NROW(x)) by which x is ordered.

References

Achim Zeileis and Gabor Grothendieck (2005). zoo: S3 Infrastructure for Regular and Irregular Time Series. Journal of Statistical Software, 14(6), 1-27. URL http://www.jstatsoft.org/v14/i06/ and available as vignette("zoo").

Ajay Shah, Achim Zeileis and Gabor Grothendieck (2005). zoo Quick Reference. Package vignette available as vignette("zoo-quickref").

See Also

zooreg, plot.zoo, index, merge.zoo

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)

## subsetting with numeric indexes
x[c(2, 4)]
## subsetting with index class
x[as.Date("2003-02-01") + c(2, 8)]

## 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)]
## subsetting with index class can be enforced by I()
x[I(c(3, 9))]

## 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

# 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

## zoo series with duplicated indexes
z3 <- zoo(1:8, c(1, 2, 2, 2, 3, 4, 5, 5))
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)]
x1[coredata(x1 > 3)]
x1[as.logical(x1 > 3)]
subset(x1, x1 > 3)


Regular zoo Series

Description

zooreg is the creator for the S3 class "zooreg" for regular "zoo" series. It inherits from "zoo" and is the analogue to ts.

Usage

zooreg(data, start = 1, end = numeric(), frequency = 1,
  deltat = 1, ts.eps = getOption("ts.eps"), order.by = NULL)

Arguments

data | a numeric vector, matrix or a factor.
start | the time of the first observation. Either a single number or a vector of two integers, which specify a natural time unit and a (1-based) number of samples into the time unit.
end | the time of the last observation, specified in the same way as start.
frequency | the number of observations per unit of time.
deltat | the fraction of the sampling period between successive observations; e.g., 1/12 for monthly data. Only one of frequency or deltat should be provided.
ts.eps | time series comparison tolerance. Frequencies are considered equal if their absolute difference is less than ts.eps.
order.by | a vector by which the observations in x are ordered. If this is specified the arguments start and end are ignored and zoo(data, order.by, frequency) is called. See zoo for more information.

Details

Strictly regular series are those whose time points are equally spaced. Weakly regular series are strictly regular time series in which some of the points may have been removed but still have the original underlying frequency associated with them. "zooreg" is a subclass of "zoo" that is used to represent both weakly and strictly regular series. Internally, it is the same as "zoo" except it also has a "frequency" attribute. Its index class is more restricted than "zoo". The index: 1. must be numeric or a class which can be coerced via as.numeric (such as yearmon, yearqtr, Date, POSIXct etc.). 2. when converted to numeric must be expressable as multiples of 1/frequency. 3. group generic functions Ops should be defined, i.e., adding/substracting a numeric to/from the index class should produce the correct value of the index class again.

zooreg is the zoo analogue to ts. The arguments are almost identical, only in the case where order.by is specified, zoo is called with zoo(data, order.by, frequency). It creates a regular series of class "zooreg" which inherits from "zoo". It is essentially a "zoo" series with an additional "frequency" attribute. In the creation of "zooreg" objects (via zoo, zooreg, or coercion functions) it is always check whether the index specified complies with the frequency specified.

The class "zooreg" offers two advantages over code "ts": 1. The index does not have to be plain numeric (although that is the default), it just must be coercable to numeric, thus printing and plotting can be customized. 2. This class can not only represent strictly regular series, but also series with an underlying regularity, i.e., where some observations from a regular grid are omitted.

Hence, "zooreg" is a bridge between "ts" and "zoo" and can be employed to coerce back and forth between the two classes. The coercion function as.zoo.ts returns therefore an object of class "zooreg" inheriting from "zoo". Coercion between "zooreg" and "zoo" is also available and drops or tries to add a frequency respectively.

For checking whether a series is strictly regular or does have an underlying regularity the generic function is.regular can be used.

Methods to standard generics for regular series such as frequency, deltat and cycle are available for both "zooreg" and "zoo" objects. In the latter case, it is checked first (in a data-driven way) whether the series is in fact regular or not.

Value

An object of class "zooreg" which inherits from "zoo". It is essentially a "zoo" series with a "frequency" attribute.

See Also

zoo, is.regular

Examples

## equivalent specifications of a quarterly series
## starting in the second quarter of 1959.
zooreg(1:10, frequency = 4, start = c(1959, 2))
as.zoo(ts(1:10, frequency = 4, start = c(1959, 2)))
zoo(1:10, seq(1959.25, 1961.5, by = 0.25), frequency = 4)

## use yearqtr class for indexing the same series
z <- zoo(1:10, yearqtr(seq(1959.25, 1961.5, by = 0.25)), frequency = 4)
z
z[-(3:4)]

## create a regular series with a "Date" index
zooreg(1:5, start = Sys.Date())
## or with "yearmon" index
zooreg(1:5, end = yearmon(2000))

## lag and diff (as it is defined in terms of lag)
## act different on zoo and zooreg objects!
x <- c(1, 4, 5, 6)
zz <- zoo(x, x)
zr <- as.zooreg(zz)
lag(zz)
lag(zr)
diff(zz)
diff(zr)

## standard methods available for regular series
frequency(z)
deltat(z)
cycle(z)
cycle(z[-(3:4)])