Title: | Time Indexes and Time Indexed Series |
---|---|
Description: | Functions and S3 classes for time indexes and time indexed series, which are compatible with FAME frequencies. |
Authors: | Jeff Hallman <[email protected]> |
Maintainer: | Brian Salzer <[email protected]> |
License: | Unlimited |
Version: | 1.39 |
Built: | 2024-10-27 06:43:24 UTC |
Source: | CRAN |
Functions and S3 classes for time indices and time indexed series, a flexible kind of time series compatible with series and frequencies understood by the FAME DBMS.
For a complete list of functions provided by this package, use
library(help="tis")
.
The ti
(Time Index) and tis
(Time Indexed Series) classes
provide date arithmetic facilities and an alternative to the somewhat
inflexible ts
class in the standard R stats package.
Time Indexes (ti
class)
A time index has two parts: a tif
(Time Index Frequency) code and
a period. tif
codes all lie in the open interval (1000..5000)
and the period is a nonnegative number less than 1e10. The ti
encodes
both, as for any ti z
unclass(z) == (tif(z) * 1e10) + period(z)
Each tif
has a particular base period (the time period where
period(z) == 0
). For example, the base period for an
"anndecember" (annual December) ti
is the year ending December
31, 1599. Periods before the base period cannot be represented by
instances of the ti
class.
If x
and y
are ti
objects with the same tif
, then
x - y == period(x) - period(y)
and
x + (period(y) - period(x)) == y
are both TRUE
, so you can use ti
's for various calendrical calculations.
A jul
class is also provided for Julian date-time objects. The jul()
constructor can create a jul
from an ssDate
(spreadsheet date), a
POSIXct
or POSIXlt
object, a ti
object, a decimal
time (like 2007.5), a yyyymmdd number, a Date
, or anything that
can be coerced to a Date
by as.Date
. The ymd()
function and its derivatives (year()
, month()
, day()
, etc.)
work on anything that jul()
can handle.
Time Indexed Series (tis
class)
The tis
class maps very closely to the FAME (http://www.sungard.com/Fame/)
database notion of what a time series is. A tis
(Time Indexed Series) is
vector or matrix indexed by a ti
. If x
is a tis
,
then start(x)
gives the ti
for the first observation, and
[start(x) + k]
is the ti
for the k'th
observation, while end(x)
gives the ti
for the last observation.
You can replace, say, the 5'th observation in a tis x
by
x[start(x) + 4] <- 42
and of course the [
operator also works with a ti
. So if
you want the value of the daily series x
from July 3, 1998, you can get it with
x[ti(19980703, "daily")]
provided, of course, that ymd(start(x)) <= 19980703 <= ymd(end(x))
.
Numerous methods for tis
objects are provided:
> methods(class = "tis") [1] aggregate.tis* as.data.frame.tis* as.matrix.tis* as.tis.tis* [5] as.ts.tis* cbind.tis* cummax.tis* cummin.tis* [9] cumprod.tis* cumsum.tis* cycle.tis* deltat.tis* [13] diff.tis* edit.tis* end.tis* frequency.tis* [17] lag.tis* lines.tis* Ops.tis* points.tis* [21] print.tis* RowMeans.tis* RowSums.tis* start.tis* [25] tifName.tis* tif.tis* time.tis* [<-.tis* [29] [.tis* ti.tis* t.tis window.tis*
as well as tisMerge
and tisPlot
functions. The
convert
function creates series of different frequencies from a
given series in ways both more powerful and more flexible than
aggregate
can.
Setting Default Frequencies:
Like the FAME DBMS, the ti
class has seven weekly frequencies for
weeks ending on Sunday, Monday, and it has 12 annual frequencies, for
years ending on the last day of each of the 12 months. There are also
multiple biweekly, bimonthly and semiannual frequencies.
At any time you can use the function setDefaultFrequencies
to change which
actual frequencies the strings "weekly", "biweekly", "bimonthly",
"quarterly", "semiannual" and "annual" refer to. Note (as shown by
args(setDefaultFrequencies)
) that if you don't specify some other frequencies
to setDefaultFrequencies
, you'll get default weeks ending on Monday and
default biweeks ending on the first Wednesday. I chose these because they
are the weeks and biweeks used most often (for money and reserves data) in my
section at the Federal Reserve Board. You might want to use something like
setHook(packageEvent("tis", "onLoad"), tis::setDefaultFrequencies(yourArgsGoHere))
in your .First()
to automatically set the defaults up the way you want them
whenever this package is loaded.
LAGS:
The stats::lag(x, k)
function says that a series lagged by a positive k starts
earlier. The opposite is true for the Lag
function in this package, to
maintain consistency with the common usage of 'first lag, second lag' and so
on in econometrics.
tisFilter
:
The stats::filter
function coerces it's argument to a ts
time series and
returns a ts
. For tis
and zoo
series, this is not right. Both I and
the author of the zoo package have requested that stats::filter
be made an S3
generic with the current version renamed as filter.default
. This would allow
zoo and tis to define filter.zoo
and
filter.tis
such that filter(aZooOrTis)
would do the right
thing. We are hopeful that this will happen soon. Meanwhile,
tisFilter
should be used to filter a tis
.
Jeff Hallman [email protected]
Maintainer: ditto
Splits the data into subsets, computes summary statistics for each, and returns the result in a convenient form.
## S3 method for class 'tis' aggregate(x, FUN = sum, ...)
## S3 method for class 'tis' aggregate(x, FUN = sum, ...)
x |
a |
FUN |
a scalar function to compute the summary statistics which can be applied to all data subsets. |
... |
further arguments passed to |
This is a method for the generic aggregate
function.
The aggregate
function was really designed for ts
objects, not tis
objects which may or may not meet the
assumptions embedded in the function. The convert
function is
better suited for tis
series.
aggregate.tis
calls as.ts
on it's x
argument,
then passes that and all other arguments on to aggregate.ts
and
then turns the result back into a tis
series. If there is a
local version of aggregate.ts
that can be found by
exists("aggregate.ts", envir = globalenv())
,
it will be used in preference to the function in package:stats
.
the tis
object returned by as.tis()
called on the
ts
object returned by aggregate.ts
.
apply
, lapply
, tapply
,
aggregate
, and convert
.
z <- tis(1:24, start = latestJanuary()) ## a monthly series aggregate(z, nf = 4, FUN = mean) ## quarterly average aggregate(z, nf = 1, FUN = function(x) x[length(x)]) ## December is annual level
z <- tis(1:24, start = latestJanuary()) ## a monthly series aggregate(z, nf = 4, FUN = mean) ## quarterly average aggregate(z, nf = 1, FUN = function(x) x[length(x)]) ## December is annual level
Coerce a Time Indexed Series to a data frame.
## S3 method for class 'tis' as.data.frame(x, ...)
## S3 method for class 'tis' as.data.frame(x, ...)
x |
a |
... |
other args passed on to |
The function is very simple: it calls
as.data.frame.matrix
if x
is a matrix, or
as.data.frame.vector
if it is not.
a data frame.
Methods to convert ti
and jul
objects to class
"Date"
representing calendar dates.
## S3 method for class 'ti' as.Date(x, offset = 1, ...) ## S3 method for class 'jul' as.Date(x, origin = "1970-01-01", ...)
## S3 method for class 'ti' as.Date(x, offset = 1, ...) ## S3 method for class 'jul' as.Date(x, origin = "1970-01-01", ...)
x |
A |
offset |
a number between 0 and 1 specifying where in the period
represented by the |
origin |
a Date object, or something which can be coerced by
|
... |
additional args passed on to
|
An object of class "Date"
.
as.Date
for the generic function,
as.Date.numeric
for the method eventually called, and Date for
details of the date class.
as.Date(today()) ## invokes as.Date.ti as.Date(jul(today() - 7)) ## a week ago, uses as.Date.jul
as.Date(today()) ## invokes as.Date.ti as.Date(jul(today() - 7)) ## a week ago, uses as.Date.jul
as.list.ti
creates a list of one-element ti
objects from
the elements of its arguments.
as.list.jul
creates a list of one-element jul
objects from
the elements of its arguments.
## S3 method for class 'ti' as.list(x, ...) ## S3 method for class 'jul' as.list(x, ...)
## S3 method for class 'ti' as.list(x, ...) ## S3 method for class 'jul' as.list(x, ...)
x |
a |
... |
not used |
These are the ti
and jul
methods for the generic as.list
.
a list of one-element ti
or jul
objects.
as.list(today() + 1:5) as.list(jul(today()) + 1:5)
as.list(today() + 1:5) as.list(jul(today()) + 1:5)
The function adds a dim
attribute of
c(length(x), 1)
to its argument unless it already has a
dim
attribute of length 2.
## S3 method for class 'tis' as.matrix(x, ...)
## S3 method for class 'tis' as.matrix(x, ...)
x |
a |
... |
ignored |
A tis
object with a dim
attribute of length 2.
Constructs a ts
object from a tis
object. The tis
object's starting year
, starting
cycle
, and frequency
, along with the object's data, in a
call to the ts
function.
## S3 method for class 'tis' as.ts(x, ...)
## S3 method for class 'tis' as.ts(x, ...)
x |
a |
... |
Ignored |
The tis
class covers more frequencies than the ts
class does, so the conversion may not be accurate.
A ts
object with the same data as x
, and with
starting time and frequency given by:
start = c(year(xstart), cycle(xstart)) frequency = frequency(x)
The tis
class covers more frequencies than the ts
class does, so the conversion may not be accurate.
Turns its argument into a list of elements with the same class as the argument.
asClassyList(x, ...)
asClassyList(x, ...)
x |
object to be coerced or tested. |
... |
objects, possibly named. |
A list L
of one-element vectors with
L[[i]] == x[i] for i in 1:length(x)
The implementation of this function is identical to
as.list.factor
. It is used in as.list.ti
and
as.list.jul
.
asClassyList(today() + 1:5)
asClassyList(today() + 1:5)
Assigns the values in a list to variables in an environment. The
variable names are taken from the names
of the list, so all of
the elements of the list must have non-blank names.
assignList(aList, pos = -1, envir = as.environment(pos), inherits = FALSE)
assignList(aList, pos = -1, envir = as.environment(pos), inherits = FALSE)
aList |
a list of values to be assigned to variables with names
given by |
pos |
where to do the assignment. By default, assigns into the current environment. |
envir |
the |
inherits |
should the enclosing frames of the environment be inspected? |
See assign
for details on how R assignment works. This
function simply uses the elements of names(aList)
and
aList
itself to call the .Internal
function used by
assign
once for each element of aList
.
This function is invoked for its side effect, which assigns values to
the variables with names given by names(aList)
.
myList <- list(a = 1, b = 2, c = 3) assignList(myList) ## equivalent to a <- 1; b <- 2; c <- 3
myList <- list(a = 1, b = 2, c = 3) assignList(myList) ## equivalent to a <- 1; b <- 2; c <- 3
This is barplot
for tis
objects. If the first argument
to barplot
is a tis
object, this function is called.
There may be more than one tis
argument. See details below.
## S3 method for class 'tis' barplot(height, ...)
## S3 method for class 'tis' barplot(height, ...)
height |
a |
... |
arguments passed on to |
barplot.tis
constructs a call to barplot2
.
The tis
arguments, including but not limited to height
,
are pulled out and used to construct a height
argument for the
constructed call, and the width
argument will be calculated as
described below.
If the series sent in are multivariate, i.e., have multiple columns,
the constructed height
argument will also have multiple
columns, which is how barplot
does stacked bar charts.
If you supply several multivariate series to
barplot.tis
, all of the series must have the same number of columns.
If the beside
argument is supplied in the ... list, the
width
argument will be set to d/(NC + 0.5)
, where
d
is the mean difference in decimal time units (where one year
= 1, a quarter = 0.25, and so on) of the series observation times,
NC
is the number of columns in the series arguments, and
space
will be set to c(0, 0.5)
. The effect of
all this will be to make the total width of the barplot match the
length (in years) of the series plotted. When combined with the
calculated x.offset
described below, this will make the plot
align correctly on the time axis. However, note that the alignment
will only really be correct if all of the series plotted have the same
frequency, as the underlying barplot.default
forces each group
of bars to have the same width when beside = TRUE
.
If the series being plotted are of different frequencies, you should
not set beside
, leaving it at the default value of
FALSE
. This will cause the widths of the bars for each series
to be inversely proportional to the series frequencies, and the
individual observations will align correctly on the time axis.
barplot.tis
finds the earliest starting date of the
tis
arguments and shifts the plot rightward along the x-axis by
that amount, which aligns the first bar with its start date. That is,
if gdp
is the tis
argument with the earliest start date of all
the series being plotted, the plot is shifted rightward to make the
first bar align with time(start(gdp))
.
You can use tisPlot
to draw axes, axis labels, and tick marks
for a barplot
. First call tisPlot
with the series
you want to plot, and other arguments set to create the range, axes,
labels, tick marks and so on that you want, but set color = 0
to make the series lines invisible. Then call barplot
with the
series and additional barplot
arguments, but set the add
argument to add = TRUE
. This adds the barplot, without axes, to
the existing tisPlot.
same as barplot.default
.
This function is a modified version of barplot
with an
additional argument that allows the bars to be shifted left or right
along the x-axis.
barplot2(height, width = 1, space = NULL, names.arg = NULL, legend.text = NULL, beside = FALSE, horiz = FALSE, density = NULL, angle = 45, col = NULL, border = par("fg"), main = NULL, sub = NULL, xlab = NULL, ylab = NULL, xlim = NULL, ylim = NULL, xpd = TRUE, log = "", axes = TRUE, axisnames = TRUE, cex.axis = par("cex.axis"), cex.names = par("cex.axis"), inside = TRUE, plot = TRUE, axis.lty = 0, offset = 0, add = FALSE, args.legend = NULL, x.offset = 0, ...)
barplot2(height, width = 1, space = NULL, names.arg = NULL, legend.text = NULL, beside = FALSE, horiz = FALSE, density = NULL, angle = 45, col = NULL, border = par("fg"), main = NULL, sub = NULL, xlab = NULL, ylab = NULL, xlim = NULL, ylim = NULL, xpd = TRUE, log = "", axes = TRUE, axisnames = TRUE, cex.axis = par("cex.axis"), cex.names = par("cex.axis"), inside = TRUE, plot = TRUE, axis.lty = 0, offset = 0, add = FALSE, args.legend = NULL, x.offset = 0, ...)
height |
either a vector or matrix of values describing the
bars which make up the plot. If |
width |
optional vector of bar widths. Re-cycled to length the
number of bars drawn. Specifying a single value will have no
visible effect unless |
space |
the amount of space (as a fraction of the average bar
width) left before each bar. May be given as a single number or
one number per bar. If |
names.arg |
a vector of names to be plotted below each bar or
group of bars. If this argument is omitted, then the names are
taken from the |
legend.text |
a vector of text used to construct a legend for
the plot, or a logical indicating whether a legend should be
included. This is only useful when |
beside |
a logical value. If |
horiz |
a logical value. If |
density |
a vector giving the density of shading lines, in
lines per inch, for the bars or bar components.
The default value of |
angle |
the slope of shading lines, given as an angle in degrees (counter-clockwise), for the bars or bar components. |
col |
a vector of colors for the bars or bar components.
By default, grey is used if |
border |
the color to be used for the border of the bars.
Use |
main , sub
|
overall and sub title for the plot. |
xlab |
a label for the x axis. |
ylab |
a label for the y axis. |
xlim |
limits for the x axis. |
ylim |
limits for the y axis. |
xpd |
logical. Should bars be allowed to go outside region? |
log |
string specifying if axis scales should be logarithmic; see
|
axes |
logical. If |
axisnames |
logical. If |
cex.axis |
expansion factor for numeric axis labels. |
cex.names |
expansion factor for axis names (bar labels). |
inside |
logical. If |
plot |
logical. If |
axis.lty |
the graphics parameter |
offset |
a vector indicating how much the bars should be shifted relative to the x axis. |
add |
logical specifying if bars should be added to an already
existing plot; defaults to |
args.legend |
list of additional arguments to pass to
|
x.offset |
shifts the plot left or right along the x-axis. |
... |
arguments to be passed to/from other methods. For the
default method these can include further arguments (such as
|
barplot2
is a slightly modified version of
barplot.default
with an additional parameter (x.offset
)
that can shift the plot left or right. It was originally written for
use by barplot.tis
, but it can now also be called on it's own.
same as barplot.default
, i.e.,
A numeric vector (or matrix, when beside = TRUE
), say
mp
, giving the coordinates of all the bar midpoints
drawn, useful for adding to the graph.
If beside
is true, use colMeans(mp)
for the
midpoints of each group of bars, see example.
tis series have (sometimes implicit) basis
and
observed
attributes, used when aggregating or disaggregating to
different frequencies.
basis(x) basis(x) <- value observed(x) observed(x) <- value
basis(x) basis(x) <- value observed(x) observed(x) <- value
x |
a |
value |
a character string, see the details |
These (optional) attributes of a tis
series are used when
converting a series from one frequency to another.
A series basis
is "business" or "daily",
indicating whether the data values in a series are associated with a
5-day business week or a 7-day calendar week.
The observed
attribute of series is one of the following:
annualized
Specifies that each time series value is the annualized sum of observations made throughout the associated time interval. For time scale conversion and totaling purposes, this attribute is the same as averaged.
averaged
Specifies that each time series value is the average of the observations made throughout the associated time interval.
beginning
Specifies that each time series value represents a single observation made at the beginning of the associated time interval.
end
Specifies that each time series value represents a single observation made at the end of the associated time interval.
formula
Specifies that the time series represents a transformation of other series. For time scale conversion and totaling purposes, this attribute is the same as averaged.
high
Specifies that each time series value is the maximum value for the time interval.
low
Specifies that each time series value is the minimum value for the time interval.
summed
Specifies that each time series value is the sum of observations made throughout the associated time interval.
basis
and observed
return a character string. The
assignment forms invisibly return x
.
The FAME documentation, available from Sungard.
Returns a logical vector like y
showing if each element
lies in the closed interval [min(x1, x2), max(x1, x2)]
.
between(y, x1, x2)
between(y, x1, x2)
y |
a numeric object |
x1 |
a number |
x2 |
a number |
A logical object like y
.
mat <- matrix(rnorm(16), 4, 4) mat between(mat, -2, 1)
mat <- matrix(rnorm(16), 4, 4) mat between(mat, -2, 1)
Takes an integer argument n
and return a string of n blanks
blanks(n)
blanks(n)
n |
an integer |
Capitalizes characters that begin strings, or that follow a character that is not digit, underscore, or letter.
capitalize(strings)
capitalize(strings)
strings |
character vector |
A character vector like strings
but capitalized.
Jeff Hallman
This is cbind
for tis
objects. It binds several
ts
and tis
objects together into a single matrix time
indexed series.
## S3 method for class 'tis' cbind(..., union = F)
## S3 method for class 'tis' cbind(..., union = F)
... |
any number of univariate or multivariate |
union |
a logical. If |
If union
is TRUE
and the series in ... do not all
start and end on the same time index, the missing observations are
filled with NA
.
The column names of the returned series are determined as follows:
If an argument was given a name in the call, the corresponding column has that name. If the argument was itself a matrix with column names, those will be used, otherwise the argument's name is expanded with digits denoting its respective columns.
a multivariate tis
object.
Class "ts"
has it's own cbind
method which knows nothing
about tis
objects. R generic functions like cbind
dispatch on the class of their first argument, so if you want to
combine tis
and ts
objects by calling the generic
cbind
, be sure that the first argument is a tis
, not a
ts
. You can always ensure this is the case by wrapping the
first argument in ... in as.tis()
.
Create lists from the rows and/or columns of a matrix.
columns(z) rows(z)
columns(z) rows(z)
z |
a matrix |
rows
returns a list of the rows of z
. If z
has
row names, those will also be the names of the returned list.
columns
does the same, but for columns. Note that if z
is some kind of time series, so too will be the elements of the
returned list.
Create tis
time series that grow at constant rates.
fanSeries(startValue, start, end, rates) tunnelSeries(startValue, start, end, rate, spreads)
fanSeries(startValue, start, end, rates) tunnelSeries(startValue, start, end, rate, spreads)
startValue |
starting value for the series at time |
start |
a |
end |
a |
rates |
annual growth rate(s) for the series to be created |
rate |
annual growth rate for the series to be created |
spreads |
vector of 2 numbers giving the percentage values by
which the starting values of the 'tunnel' series should be offset from
|
fanSeries
returns a multivariate series that starts on
start
and ends on end
. There are length(rates)
columns. Each column begins at startValue
and grows at the rate
given by its corresponding element in rates
. These are not
true growth rates, rather each column has a constant first difference
such that over the course of the first year, column i will grow
rates[i]
percent. This yields series that plot as straight
lines.
tunnelSeries
first calls fanSeries
to create a
univariate series running from start
to end
with a
starting value of startValue
and growing rate
percent
over the first year. It returns a bivariate series with columns that are
offset from that series by spreads[1]
and spreads[2]
percent of the startValue
.
Convert tis
series from one frequency to another using a
variety of algorithms.
convert(x, tif, method = "constant", observed. = observed(x), basis. = basis(x), ignore = F)
convert(x, tif, method = "constant", observed. = observed(x), basis. = basis(x), ignore = F)
x |
a univariate or multivariate |
tif |
a number or a string indicating the desired ti frequency of the
return series. See |
method |
method by which the conversion is done: one of "discrete",
"constant", "linear", or "cubic". Note that this argument is
effectively ignored if |
observed. |
"observed" attribute of the input series: one of "beginning", "end",
"high", "low", "summed", "annualized", or "averaged". If this argument is not
supplied and observed( |
basis. |
"daily" or "business". If this argument is not supplied and
basis( |
ignore |
governs how missing (partial period) values at the beginning and/or end of the series are handled. For method == "discrete" or "constant" and ignore == T, input values that cover only part the first and/or last output time intervals will still result in output values for those intervals. This can be problematic, especially for observed == "summed", as it can lead to atypical values for the first and/or last periods of the output series. |
This function is a close imitation of the way FAME handles time scale conversions. See the chapter on "Time Scale Conversion" in the Users Guide to Fame if the explanation given here is not detailed enough.
Start with some definitions. Combining values of a higher frequency
input series to create a lower frequency output series is known as
aggregation
. Doing the opposite is known as disaggregation
.
If observed == "high" or "low", the "discrete" method is always used.
Disaggration for "discrete" series: (i) for observed == "beginning" ("end"), the first (last) output period that begins (ends) in a particular input period is assigned the value of that input period. All other output periods that begin (end) in that input period are NA. (ii) for observed == "high", "low", "summed" or "averaged", all output periods that end in a particular input period are assigned the same value. For "summed", that value is the input period value divided by the number of output periods that end in the input period, while for "high", "low" and "averaged" series, the output period values are the same as the corresponding input period values.
Aggregation for "discrete" series: (i) for observed == "beginning" ("end"), the output period is assigned the value of the first (last) input period that begins (ends) in the output period. (ii) for observed == "high" ("low"), the output period is assigned the value of the maximum (minimum) of all the input values for periods that end in the output period. (iii) for observed == "summed" ("averaged"), the output value is the sum (average) of all the input values for periods that end in the output period.
Methods "constant", "linear", and "cubic" all work by constructing a
continuous function F(t) and then reading off the appropriate
point-in-time values if observed == "beginning" or "end", or by
integrating F(t) over the output intervals when observed == "summed",
or by integrating F(t) over the output intervals and dividing by the
lengths of those intervals when observed == "averaged". The unit of
time itself is given by the basis
argument.
The form of F(t) is determined by the conversion method. For "constant" conversions, F(t) is a step function with jumps at the boundaries of the input periods. If the first and/or last input periods only partly cover an output period, F is linearly extended to cover the first and last output periods as well. The heights of the steps are set such that F(t) aggregates over the input periods to the original input series.
For "linear" ("cubic") conversions, F(t) is a linear (cubic) spline. The x-coordinates of the spline knots are the beginnings or ends of the input periods if observed == "beginning" or "end", else they are the centers of the input periods. The y-coordinates of the splines are chosen such that aggregating the resulting F(t) over the input periods yields the original input series.
For "constant" conversions, if ignore
== F, the first (last)
output period is the first (last) one for which complete input data is
available. For observed == "beginning", for example, this means that
data for the first input period that begins in the first output period
is available, while for observed == "summed", this means that the
first output period is completely contained within the available input
periods. If ignore
== T, data for only a single input period
is sufficient to create an output period value. For example, if
converting weekly data to monthly data, and the last observation is
June 14, the output series will end in June if ignore
== T, or
May if it is F.
Unlike the "constant" method, the domain of F(t) for "linear" and "cubic" conversions is NOT extended beyond the input periods, even if the ignore option is T. The first (last) output period is therefore the first (last) one that is completely covered by input periods.
Series with observed == "annualized" are handled the same as observed == "averaged".
a tis
time series covering approximately the same time span as
x
, but with the frequency specified by tif
.
Method "cubic" is not currently implemented for observed "summed", "annualized", and "averaged".
Users Guide to Fame
wSeries <- tis(1:105, start = ti(19950107, tif = "wsaturday")) observed(wSeries) <- "ending" ## end of week values mDiscrete <- convert(wSeries, "monthly", method = "discrete") mConstant <- convert(wSeries, "monthly", method = "constant") mLinear <- convert(wSeries, "monthly", method = "linear") mCubic <- convert(wSeries, "monthly", method = "cubic") ## linear and cubic are identical because wSeries is a pure linear trend cbind(mDiscrete, mConstant, mLinear, mCubic) observed(wSeries) <- "averaged" ## weekly averages mDiscrete <- convert(wSeries, "monthly", method = "discrete") mConstant <- convert(wSeries, "monthly", method = "constant") mLinear <- convert(wSeries, "monthly", method = "linear") cbind(mDiscrete, mConstant, mLinear)
wSeries <- tis(1:105, start = ti(19950107, tif = "wsaturday")) observed(wSeries) <- "ending" ## end of week values mDiscrete <- convert(wSeries, "monthly", method = "discrete") mConstant <- convert(wSeries, "monthly", method = "constant") mLinear <- convert(wSeries, "monthly", method = "linear") mCubic <- convert(wSeries, "monthly", method = "cubic") ## linear and cubic are identical because wSeries is a pure linear trend cbind(mDiscrete, mConstant, mLinear, mCubic) observed(wSeries) <- "averaged" ## weekly averages mDiscrete <- convert(wSeries, "monthly", method = "discrete") mConstant <- convert(wSeries, "monthly", method = "constant") mLinear <- convert(wSeries, "monthly", method = "linear") cbind(mDiscrete, mConstant, mLinear)
Write a matrix or Time Indexed Series to a .csv file that can be imported into a spreadsheet.
csv(z, file = "", noDates = FALSE, row.names = !is.tis(z), ...)
csv(z, file = "", noDates = FALSE, row.names = !is.tis(z), ...)
z |
matrix or |
file |
either a character string naming a file or a connection. If
|
noDates |
logical. If |
row.names |
either a logical value indicating whether the row names of
|
... |
other arguments passed on to |
csv
is essentially a convenient way to call write.table
.
If file
is not a connection, a file name with the ".csv"
extension is constructed. Next, a column of spreadsheet dates is
prepended to z
if necessary, and then csv
calls
write.table(z, file = filename, sep = ",", row.names = !is.tis(z), ...)
csv
returns whatever the call to write.table
returned.
Return a tis
whose elements are the cumulative sums, products,
minima or maxima of the elements of the argument.
## S3 method for class 'tis' cumsum(x) ## S3 method for class 'tis' cumprod(x) ## S3 method for class 'tis' cummax(x) ## S3 method for class 'tis' cummin(x)
## S3 method for class 'tis' cumsum(x) ## S3 method for class 'tis' cumprod(x) ## S3 method for class 'tis' cummax(x) ## S3 method for class 'tis' cummin(x)
x |
a |
These are tis
methods for generic functions.
A tis
like x
. An NA
value in x
causes the
corresponding and following elements of the return value to be
NA
, as does integer overflow in cumsum
(with a warning).
cumsum
, cumprod
,
cummin
, cummax
Return daily ti
's for particular days of the week
currentMonday(xTi = today()) currentTuesday(xTi = today()) currentWednesday(xTi = today()) currentThursday(xTi = today()) currentFriday(xTi = today()) currentSaturday(xTi = today()) currentSunday(xTi = today()) latestMonday(xTi = today()) latestTuesday(xTi = today()) latestWednesday(xTi = today()) latestThursday(xTi = today()) latestFriday(xTi = today()) latestSaturday(xTi = today()) latestSunday(xTi = today())
currentMonday(xTi = today()) currentTuesday(xTi = today()) currentWednesday(xTi = today()) currentThursday(xTi = today()) currentFriday(xTi = today()) currentSaturday(xTi = today()) currentSunday(xTi = today()) latestMonday(xTi = today()) latestTuesday(xTi = today()) latestWednesday(xTi = today()) latestThursday(xTi = today()) latestFriday(xTi = today()) latestSaturday(xTi = today()) latestSunday(xTi = today())
xTi |
a |
currentMonday
returns the daily ti
for the last day of
the Monday-ending week that its argument falls into.
currentTuesday
returns the daily ti
for the last day of
the Tuesday-ending week that its argument falls into, and so on for
the other weekdays.
latestMonday
returns the daily ti
for the last day of
the most recent completed Monday-ending week that its argument falls
into. Ditto for the other days of the week.
Return a current ti
of the desired frequency
currentWeek(xTi = today()) currentMonth(xTi = today()) currentQuarter(xTi = today()) currentHalf(xTi = today()) currentYear(xTi = today()) currentQ4(xTi = today()) currentQMonth(xTi = today()) currentJanuary(xTi = today()) currentFebruary(xTi = today()) currentMarch(xTi = today()) currentApril(xTi = today()) currentMay(xTi = today()) currentJune(xTi = today()) currentJuly(xTi = today()) currentAugust(xTi = today()) currentSeptember(xTi = today()) currentOctober(xTi = today()) currentNovember(xTi = today()) currentDecember(xTi = today())
currentWeek(xTi = today()) currentMonth(xTi = today()) currentQuarter(xTi = today()) currentHalf(xTi = today()) currentYear(xTi = today()) currentQ4(xTi = today()) currentQMonth(xTi = today()) currentJanuary(xTi = today()) currentFebruary(xTi = today()) currentMarch(xTi = today()) currentApril(xTi = today()) currentMay(xTi = today()) currentJune(xTi = today()) currentJuly(xTi = today()) currentAugust(xTi = today()) currentSeptember(xTi = today()) currentOctober(xTi = today()) currentNovember(xTi = today()) currentDecember(xTi = today())
xTi |
a |
currentWeek
returns the weekly ti
for the week that its
argument falls into. If the argument is itself a ti
, the
returned week contains the last day of the argument's period. The default
weekly frequency is "wmonday" (Monday-ending weeks), so
currentWeek
always returns wmonday ti
's. This can be
changed via the setDefaultFrequencies
function.
All of the other current{SomeFreq}
functions work the same way,
returning the ti
's of tif
SomeFreq that the last day of
their arguments period falls into. The tif
's for
currentHalf
and currentQ4
are "semiannual" and
"quarterly", respectively. Finally, currentQMonth
returns the
quarter-ending month of the currentQuarter
of its argument.
currentJanuary
returns the monthly ti
for January of the
January-ending year that the last day of its argument falls into.
currentFebruary
returns the monthly ti
for February of
the February-ending year that the last day of its argument falls into,
and so on.
All return return ti
objects as described in the details.
ti
, tif
,
latestWeek
setDefaultFrequencies
Returns the starting and ending times of a series in a
ti
object of length 2.
dateRange(x)
dateRange(x)
x |
a |
a ti
(Time Index) object of length two. The first element
is the starting time index, while the second is the ending time index.
aTs <- ts(1:24, start = c(2001, 1), freq = 12) aTis <- as.tis(aTs) dateRange(aTs) dateRange(aTis)
aTs <- ts(1:24, start = c(2001, 1), freq = 12) aTis <- as.tis(aTs) dateRange(aTs) dateRange(aTis)
Return position within a ti
period, or a particular
day within the period.
dayOfPeriod(xTi = today(), tif = NULL) dayOfWeek(xTi = today()) dayOfMonth(xTi = today()) dayOfYear(xTi = today()) firstDayOf(xTi) lastDayOf(xTi) firstBusinessDayOf(xTi) lastBusinessDayOf(xTi) firstBusinessDayOfMonth(xTi) lastBusinessDayOfMonth(xTi) currentMonthDay(xTi, daynum) latestMonthDay(xTi, daynum)
dayOfPeriod(xTi = today(), tif = NULL) dayOfWeek(xTi = today()) dayOfMonth(xTi = today()) dayOfYear(xTi = today()) firstDayOf(xTi) lastDayOf(xTi) firstBusinessDayOf(xTi) lastBusinessDayOf(xTi) firstBusinessDayOfMonth(xTi) lastBusinessDayOfMonth(xTi) currentMonthDay(xTi, daynum) latestMonthDay(xTi, daynum)
xTi |
a |
tif |
a time index frequency code or name. See |
daynum |
day number in month |
The dayOfXXXXX
functions all work the same way, returning the
day number of the XXXXX that jul(xTi)
falls on. For example,
if today is Thursday, January 5, 2006, then dayOfWeek()
,
dayOfMonth()
and dayOfYear()
are all 5. All of these
are implemented via dayOfPeriod
, which converts its first
argument to a Julian date (via jul(xTi)
) and finds the
ti
with frequency tif
that day falls into. It returns
the day number of the period represented by that time index that the
Julian date falls on.
firstDayOf
and lastDayOf
return a daily ti
for
the first or last day of the period represented by xTi
.
firstBusinessDayOf
and lastBusinessDayOf
do the same but
the returned ti
has business daily frequency.
firstBusinessDayOfMonth
returns a business daily ti
for
the first business day of the month of xTi
.
lastBusinessDayOfMonth
does the same but for the last business
day of the month of xTi
.
currentMonthDay
returns a daily ti
for the next upcoming
daynum
'th of the month. latestMonthDay
does the same
for the most recent daynum
'th of the month.
currentMonday
returns the daily ti
for the last day of
the Monday-ending week that its argument falls into. The other
current{Weekday}
functions work the same way.
All of the functions except the dayOfXXXXX
return ti
objects as described in the details section above. The
dayOfXXXXX
functions return numbers.
None of these business-day functions take account of holidays, so
firstBusinessDayOfMonth(20010101)
, for example, returns January
1, 2001 which was actually a holiday. To see how to handle holidays,
look at the holidays
and nextBusinessDay
help pages.
ti
, tif
, jul
,
holidays
, nextBusinessDay
,
previousBusinessDay
Get or set the description
and documentation
strings for an object.
description(x) description(x) <- value documentation(x) documentation(x) <- value
description(x) description(x) <- value documentation(x) documentation(x) <- value
x |
object whose description or documentation attribute is to be set or retrieved |
value |
a string |
The setters invisibly return x
, the getters return the desired
attribute or NULL.
This function parses, evaluates and returns the string given as its
first argument. If it can't, the argument itself is returned. Use of
evalOrEcho
to process arguments inside a function can make for
more flexible code.
evalOrEcho(x, resultMode = NULL, n = 0)
evalOrEcho(x, resultMode = NULL, n = 0)
x |
a string or other object to attempt to parse and evaluate. |
resultMode |
a string or NULL. If non-NULL, the evaluation of |
n |
parent generations to go back. The evaluation is attempted in the
enviroment specified by |
Using this function inside another function to process some of its
arguments can be very useful. For example, tisPlot
has a
number or arguments that specify text labels for headers, subheaders,
footnotes, axis labels, and so on. One of those arguments is
sub
, which specifies the subheader. By doing this:
sub <- evalOrEcho(sub, resultMode = "character")
tisPlot
can handle the sub
argument given in any of
these forms:
sub = "This is a simple subtitle"
.
sub = c("this is a two", "line subtitle")
.
sub = 'c("this is another", "two line subtitle")'
.
If x
is successfully parsed and evaluated, and its mode matches
resultMode
(if supplied), the resulting object is returned.
Otherwise, x
itself is returned.
format
formats a jul or time index object for printing.
as.character
for a jul
or ti
object is
essentially just an alias for format
.
## S3 method for class 'ti' format(x, ..., tz = "") ## S3 method for class 'jul' format(x, ...) ## S3 method for class 'ti' as.character(x, ...) ## S3 method for class 'jul' as.character(x, ...)
## S3 method for class 'ti' format(x, ..., tz = "") ## S3 method for class 'jul' format(x, ...) ## S3 method for class 'ti' as.character(x, ...) ## S3 method for class 'jul' as.character(x, ...)
x |
a |
tz |
A timezone specification to be used for the conversion if
|
... |
other args passed on to |
The as.character
methods do nothing but call the corresponding
format
methods.
x
is converted to a POSIXlt
object and then
format.POSIXlt
takes over.
a character vector representing x
format.POSIXlt
has been modified to understand two additional
format symbols in addition to those documented in
link{strftime}
: "%q" in the format string is replaced with the
quarter number (1 thru 4) and "%N" is replaced with the first letter
of the month name.
format(today() + 0:9, "%x") as.character(jul(today()))
format(today() + 0:9, "%x") as.character(jul(today()))
A fortify method for tis objects
## S3 method for class 'tis' fortify(x, offset = 0.5, dfNames = NULL, timeName = "date")
## S3 method for class 'tis' fortify(x, offset = 0.5, dfNames = NULL, timeName = "date")
x |
A |
offset |
A number between 0 and 1 specifying where in the period of time
represented by the 'ti(x)' the points should eventually be plotted in |
dfNames |
A character vector of the names for the |
timeName |
A character vector of length one with the desired name for
the column of dates that will be created from the |
This function turns a tis
object into a data frame containing the
original time series plus a field of dates
adjusted by an ‘offset’,
so that the time series can be more easily plotted with ggplot2
.
Trevor Davis
if(require("ggplot2") && require("reshape")) { # Examples of plotting tis series with ggplot2 require("datasets") require("scales") # univariate example num_discoveries <- as.tis(discoveries) ggplot(data = fortify(num_discoveries, offset=0)) + geom_line(aes(x=date, y=num_discoveries)) + scale_x_date(breaks = date_breaks("10 years"), labels = date_format("%Y")) # multivariate example using the "melt trick" Seatbelts.tis <- as.tis(Seatbelts[ , c("drivers", "front", "rear")]) Seatbelt.names <- c("Driver", "Front Seat Passenger", "Back Seat Passenger") Seatbelts.df <- fortify(Seatbelts.tis, dfNames = Seatbelt.names, timeName = "Time") Seatbelts.dfm <- melt(Seatbelts.df, id.var = "Time", variable_name="type") qplot( Time, value, data = Seatbelts.dfm, geom="line", group=type, colour=type, linetype=type ) + geom_vline(xintercept=as.numeric(as.Date("1983-01-31")), colour="black", linetype="dashed") + ylab("Monthly Road Casulties in the UK") }
if(require("ggplot2") && require("reshape")) { # Examples of plotting tis series with ggplot2 require("datasets") require("scales") # univariate example num_discoveries <- as.tis(discoveries) ggplot(data = fortify(num_discoveries, offset=0)) + geom_line(aes(x=date, y=num_discoveries)) + scale_x_date(breaks = date_breaks("10 years"), labels = date_format("%Y")) # multivariate example using the "melt trick" Seatbelts.tis <- as.tis(Seatbelts[ , c("drivers", "front", "rear")]) Seatbelt.names <- c("Driver", "Front Seat Passenger", "Back Seat Passenger") Seatbelts.df <- fortify(Seatbelts.tis, dfNames = Seatbelt.names, timeName = "Time") Seatbelts.dfm <- melt(Seatbelts.df, id.var = "Time", variable_name="type") qplot( Time, value, data = Seatbelts.dfm, geom="line", group=type, colour=type, linetype=type ) + geom_vline(xintercept=as.numeric(as.Date("1983-01-31")), colour="black", linetype="dashed") + ylab("Monthly Road Casulties in the UK") }
Returns a vector of 11 color names that can be used as a palette suitably for a light or dark background.
frColors(dark = FALSE)
frColors(dark = FALSE)
dark |
If |
A vector of 11 color names.
Jeff Hallman
plot.new() for(i in 1:11) abline(h = (i-0.5)/11, lwd = 2, lty = 1, col = frColors()[i]) plot.new() for(i in 1:11) abline(h = (i-0.5)/11, lwd = 2, lty = 1, col = frColors(dark = TRUE)[i])
plot.new() for(i in 1:11) abline(h = (i-0.5)/11, lwd = 2, lty = 1, col = frColors()[i]) plot.new() for(i in 1:11) abline(h = (i-0.5)/11, lwd = 2, lty = 1, col = frColors(dark = TRUE)[i])
Get or set growth rates of a tis
time series in annual
percent terms.
growth.rate(x, lag = 1, simple = T) growth.rate(x, start = end(x) + 1, simple = T) <- value
growth.rate(x, lag = 1, simple = T) growth.rate(x, start = end(x) + 1, simple = T) <- value
x |
a |
lag |
number of lags to use in calculating the growth rate as outlined in the details below |
simple |
simple growth rates if |
start |
the first |
value |
desired growth rates |
An example: Suppose x
is a quarterly series, then if simple
is
TRUE
,
growth.rate(x, lag = 3)
== 100 * ((x[t]/x[t-3]) - 1) * (4/3)
while if simple
is FALSE
growth.rate(x, lag = 3)
== 100 * ((x[t]/x[t-3])^(4/3) - 1)
.
growth.rate(x)
returns a tis
series of growth rates in
annual percentage terms.
Beginning with the observation indexed by start
,
growth.rate(x) <- value
sets the values of x
such that the growth rates in annual
percentage terms will be equal to value
. x
is extended
if necessary. The modified x
is invisibly returned.
Extract the fractional part of a ti
(time index) or
jul
(julian date) object as a normalized list of hours,
minutes, and seconds.
hms(x)
hms(x)
x |
a |
The fractional part of x
is multiplied by 86400 (the
number of seconds in a day) and rounded to get the number of seconds.
This is then divided by 3600 to get the number of hours, and the
remainder of that is divided by 60 to get the normalized number of
minutes. The remainder from the second division is the normalized
number of seconds.
A list with components:
hours |
Normalized number of hours |
minutes |
Normalized number of minutes |
seconds |
Normalized number of seconds |
See the details.
Support for fractional days in ti
and jul
objects is
relatively new and untested. There is probably code lurking about
that assumes the numeric parts of ti
and jul
objects are
integers, or even code that may round them to make sure they are
integers. The fractional parts of ti
and jul
objects
may not survive encounters with such code.
ti
and jul
. Also see
hourly
for information on intraday frequencies
hms(today() + 0.5) hms(today()) hms(today() + 43201/86400)
hms(today() + 0.5) hms(today()) hms(today() + 43201/86400)
Functions that know about Federal and FRB (Federal Reserve Board) holidays.
nextBusinessDay(x, holidays = NULL, goodFriday = F, board = F, inaug = board) previousBusinessDay(x, holidays = NULL, goodFriday = F, board = F, inaug = board) isHoliday(x, goodFriday = F, board = F, inaug = board, businessOnly = T) isBusinessDay(x, ...) isGoodFriday(x) isEaster(x) holidays(years, goodFriday = F, board = F, inaug = board, businessOnly = T) federalHolidays(years, board = F, businessOnly = T) goodFriday(years) easter(years) inaugurationDay(years) holidaysBetween(startTi, endTi, goodFriday = F, board = F, inaug = board, businessOnly = T)
nextBusinessDay(x, holidays = NULL, goodFriday = F, board = F, inaug = board) previousBusinessDay(x, holidays = NULL, goodFriday = F, board = F, inaug = board) isHoliday(x, goodFriday = F, board = F, inaug = board, businessOnly = T) isBusinessDay(x, ...) isGoodFriday(x) isEaster(x) holidays(years, goodFriday = F, board = F, inaug = board, businessOnly = T) federalHolidays(years, board = F, businessOnly = T) goodFriday(years) easter(years) inaugurationDay(years) holidaysBetween(startTi, endTi, goodFriday = F, board = F, inaug = board, businessOnly = T)
x |
a |
holidays |
a vector of holidays (in yyyymmdd form) to skip over, or
|
goodFriday |
if |
board |
if |
inaug |
if |
businessOnly |
if |
... |
arguments passed on to |
years |
numeric vector of 4 digit years |
startTi |
a daily |
endTi |
a daily |
Federal law defines 10 holidays. Four of them, NewYears, Independence, Veterans and Christmas, fall on the same date every year. The other six fall on particular days of the week and months (MLK, Presidents, Memorial, Labor, Columbus, and Thanksgiving).
If one of the four fixed-date holidays falls on a Sunday, the federal holiday is celebrated the next day (Monday). If it falls on a Saturday, the preceding day (Friday) is a holiday for the Federal Reserve Board, but not for the Reserve Banks and the banking system as a whole.
Presidential Inauguration day is a Federal holiday only in the DC
area, and then only if it falls on a weekday, so it is not included in
the holidays returned by federalHolidays
, but it can be
included in several of the other functions by setting the inaug
argument to TRUE
.
The function isBusinessDay
returns TRUE
for x
if
and only if x
is not a holiday, a Saturday or a Sunday.
nextBusinessDay
and previousBusinessDay
return
"business" frequency ti
objects.
isHoliday
, isGoodFriday
, isEaster
and isBusinessDay
return
Boolean vectors as long as x
.
easter
and goodFriday
return numeric vectors of yyyymmdd
dates of the appropiate holidays for each year in the years
argument.
inaugurationDay
returns a numeric vector of yyyymmdd dates of
U.S. Presidential Inauguration Days, if any, that fall in the years
given in the years
argument.
federalHolidays
returns a numeric vector of yyyymmdd dates
for the federal holidays for each year in years
. The
names
attribute of the returned vector contains the holiday
names.
holidays
returns a vector like federalHolidays
does.
The only difference between the two functions is that holidays
has the option of including Good Fridays.
holidaysBetween
returns a vector of yyyymmdd dates for holidays
that fall within the time spanned by [startTi, endTi]
.
The algorithm for finding Easter dates was found somewhere on the web (I don't remember where) and is unbelievably complex. It would probably be simpler to just celebrate the home opener of the Cleveland Indians instead.
Attempts to find a tif
(Time Index Frequency) that "fits" the
supplied dateTimes, and returns a ti
object that hits the same
dates and/or times.
inferTi(dateTimes)
inferTi(dateTimes)
dateTimes |
a vector |
a ti
object as long as the input
May fail if there is no tif
that closely matches the inputs.
inferTi(Sys.time() + (1:5)*86400)
inferTi(Sys.time() + (1:5)*86400)
Calls approxfun
or splinefun
to interpolate missing values in a tis
object.
interpNA(x, method = "constant", useTimes = F, offset = 1, rule = 2, f = 0, ...)
interpNA(x, method = "constant", useTimes = F, offset = 1, rule = 2, f = 0, ...)
x |
a |
method |
One of c("constant", "linear", "fmm", "natural",
"periodic"). Methods "constant" and "linear" call |
useTimes |
if |
offset |
if |
rule |
For methods "constant" and "linear": an integer describing
how interpolation is to take place outside the interval
[ |
f |
For |
... |
Other arguments passed along to |
Depending on the method specified, a call to either
approxfun
or splinefun
is constructed with appropriate
arguments and executed for each column of x
. In the call to
approxfun
or splinefun
, the time indices ti(x)
(or the decimal times returned by time(x, offset)
, if
useTimes
is TRUE
) serve as the 'x' argument and the
column values as the 'y' argument.
A tis
object like x
with NA
values filled
in by interpolated values.
create tif
(TimeIndexFrequency) codes for hourly, minutely, and
secondly ti
's.
hourly(n = 0) minutely(n = 0) secondly(n = 0)
hourly(n = 0) minutely(n = 0) secondly(n = 0)
n |
number of base periods to skip. That is, |
The current implementation has hourly(n) –> 2000 + n,
minutely(n) –> 3000 + n, and secondly(n) –> 4000 + n. If n
divides evenly into 3600 for secondly(n)
, the return code will
be the same as hourly(n/3600)
. For secondly(n)
and
minutely(n)
, if n
divides evenly into 60, the return
code will be as if minutely(n/60)
or hourly(n/60)
had
been called, respectively.
For hourly(n)
, n
must evenly divide into 24 and be less
than 24, i.e., n
is one of 1, 2, 3, 4, 6, 8, 12. For
minutely(n)
, n
must be an even divisor of 1440, and less
than 720. For secondly(n)
, n
must divide evenly into
86400, and be no larger than 960.
An integer tif
code.
The intraday frequencies are hourly(n)
,
minutely(n)
and secondly(n)
, where n
is an
appropriate integer. Their numeric tif
codes are between 2000
and 4900, and that is what is actually checked for.
isIntradayTif(tif)
isIntradayTif(tif)
tif |
a character vector of |
A logical vector as long as the input indicating which elements are intraday Time Index frequencies.
The function does not attempt to verify if the supplied tif
is actually valid, intraday or not.
isIntradayTif(hourly(6)) isIntradayTif(tif(today())) isIntradayTif(minutely(30))
isIntradayTif(hourly(6)) isIntradayTif(tif(today())) isIntradayTif(minutely(30))
Checks whether or not the elements of its input are leap years.
isLeapYear(y)
isLeapYear(y)
y |
numeric vector of years |
y
is a leap year if it is evenly divisible by 4
and either it is not evenly divisible by 100 or it is evenly
divisible by 400, i.e.,
y%%4 == 0 & (y%%100 != 0 | y%%400 == 0)
.
logical vector of same length as y
indicating whether or not
the given years are leap years.
isLeapYear(c(1899:2004))
isLeapYear(c(1899:2004))
The function jul
is used to create jul
(julian date)
objects, which are useful for date calculations.
as.jul
and asJul
coerce an object to class "jul", the
difference being that as.jul
calls the constructor jul
,
while asJul
simply forces the class of its argument to be "jul"
without any checking as to whether or not it makes sense to do so.
is.jul
tests whether an object inherits from class "jul".
jul(x, ...) ## S3 method for class 'Date' jul(x, ...) ## S3 method for class 'IDate' jul(x, ...) ## S3 method for class 'ti' jul(x, offset = 1, ...) ## S3 method for class 'yearmon' jul(x, offset = 0, ...) ## S3 method for class 'yearqtr' jul(x, offset = 0, ...) ## Default S3 method: jul(x, ...) as.jul(x, ...) asJul(x) is.jul(x)
jul(x, ...) ## S3 method for class 'Date' jul(x, ...) ## S3 method for class 'IDate' jul(x, ...) ## S3 method for class 'ti' jul(x, offset = 1, ...) ## S3 method for class 'yearmon' jul(x, offset = 0, ...) ## S3 method for class 'yearqtr' jul(x, offset = 0, ...) ## Default S3 method: jul(x, ...) as.jul(x, ...) asJul(x) is.jul(x)
x |
object to be tested ( |
... |
other args to be passed to the method called by the generic
function. |
offset |
For
|
The jul
's for any pair of valid dates differ by the number of
days between them. R's Date
class defines a Date as a number
of days elapsed since January 1, 1970, but jul
uses the
encoding from the Numerical Recipes book, which has Jan 1, 1970
= 2440588, and the code for converting between ymd and jul
representations is a straightforward port of the code from that tome.
Adding an integer to, or subtracting an integer from a jul
results in another jul
, and one jul
can be subtracted
from another. Two jul
's can also be compared with the
operators (==, !=, <. >, <=, >=
).
The jul
class implements methods for a number of generic
functions, including "["
, as.Date
, as.POSIXct
,
as.POSIXlt
, c
, format
, max
,
min
, print
, rep
, seq
, ti
,
time
, ymd
.
jul
is a generic function with specialized methods to handle
Date
and ti
objects. A recent addition is a method to
handle IDate
objects as defined in the data.table
package.
The default method (jul.default
) deals with character x
by
calling as.Date
on it. Otherwise, it proceeds as follows:
If x
is numeric, isYmd
is used to see if it could be
yyyymmdd date, then isTime
is called to see if x
could
be a decimal time (a number between 1799 and 2200). If all else fails,
as.Date(x)
is called to attempt to create a Date
object
that can then be used to construct a jul
.
is.jul
returns TRUE
or FALSE
.
as.jul
and asJul
return objects with class "jul".
jul
constructs a jul
object like x
.
jul
with no arguments returns the jul
for the current day.
The return value from asJul
is not guaranteed to be a valid
jul
object. For example, asJul("a")
will not throw an
error, and it will return the string "a" with a class attribute "jul",
but that's not a valid julian date.
The Julian calendar adopted by the Roman Republic was not accurate with respect to the rotational position of the Earth around the sun. By 1582 it had drifted ten days off. To fix this, Pope Gregory XIII decreed that the day after October 4, 1582 would be October 15, and that thereafter, leap years would be omitted in years divisible by 100 but not divisible by 400. This modification became known as the Gregorian calendar. England and the colonies did not switch over until 1752, by which time the drift had worsened by another day, so that England had to skip over 11 days, rather than 10.
The algorithms used in jul2ymd
and ymd2jul
cut over at
the end of October 1582.
Press, W. H., Teukolsky, S. A., Vetterling, W. T., and Flannery, B. P. (1992). Numerical Recipes: The Art of Scientific Computing (Second Edition). Cambridge University Press.
dec31 <- jul(20041231) jan30 <- jul("2005-1-30") jan30 - dec31 ## 30 feb28 <- jan30 + 29 jul() ## current date
dec31 <- jul(20041231) jan30 <- jul("2005-1-30") jan30 - dec31 ## 30 feb28 <- jan30 + 29 jul() ## current date
lag
creates a lagged version of a time series, shifting the time base
forward by a given number of observations. Lag
does exactly the
opposite, shifting the time base backwards by the given number of
observations. lag
and Lag
create a single lagged
series, while lags
and Lags
can create a multivariate
series with several lags at once.
## S3 method for class 'tis' lag(x, k = 1, ...) Lag(x, k = 1, ...) lags(x, lags, name = "") Lags(x, lags, name = "")
## S3 method for class 'tis' lag(x, k = 1, ...) Lag(x, k = 1, ...) lags(x, lags, name = "") Lags(x, lags, name = "")
x |
A vector or matrix or univariate or multivariate time series
(including |
k |
The number of lags. For |
... |
further arguments to be passed to or from methods |
lags |
vector of lag numbers. For code |
name |
string or a character vector of names to be used in constructing column names for the returned series |
Vector or matrix arguments 'x' are coerced to time series.
For lags
, column names are constructed as follows: If
name
is supplied and has as many elements as x
has
columns, those names are used as the base column names. Otherwise the
column names of x
comprise the base column names, or if those
don't exist, the first ncols(x)
letters of the alphabet are
used as base names. Each column of the returned series has a name
consisting of the basename plus a suffix indicating the lag number for
that column.
Both functions return a time series (ts
or tis
) object.
If the lags
argument to the lags
function argument has
more than one element, the returned object will have a column for each
lag, with NA
's filling in where appropriate.
Return a ti
for the most recent period of the
desired frequency.
latestWeek(xTi = today()) latestMonth(xTi = today()) latestQuarter(xTi = today()) latestHalf(xTi = today()) latestYear(xTi = today()) latestQ4(xTi = today()) latestJanuary(xTi = today()) latestFebruary(xTi = today()) latestMarch(xTi = today()) latestApril(xTi = today()) latestMay(xTi = today()) latestJune(xTi = today()) latestJuly(xTi = today()) latestAugust(xTi = today()) latestSeptember(xTi = today()) latestOctober(xTi = today()) latestNovember(xTi = today()) latestDecember(xTi = today())
latestWeek(xTi = today()) latestMonth(xTi = today()) latestQuarter(xTi = today()) latestHalf(xTi = today()) latestYear(xTi = today()) latestQ4(xTi = today()) latestJanuary(xTi = today()) latestFebruary(xTi = today()) latestMarch(xTi = today()) latestApril(xTi = today()) latestMay(xTi = today()) latestJune(xTi = today()) latestJuly(xTi = today()) latestAugust(xTi = today()) latestSeptember(xTi = today()) latestOctober(xTi = today()) latestNovember(xTi = today()) latestDecember(xTi = today())
xTi |
a |
The latest{whatever}
functions are the same as the
corresponding current{whatever}
functions, except that they
return the most recent completed ti
of the desired frequency.
A period is considered to be completed on it last day. For example,
if today is Thursday, then latestWedweek()
returns the week
that ended yesterday. Yesterday it would have returned the same week,
but the day before that (Tuesday) it would have returned the
"wwednesday" ti
for the week that had ended six days before.
latestWeek
returns the weekly ti
for the most recently
completed week as of xTi
. If the xTi
is itself a
ti
, the returned week is the most recently completed week as of
the last day of xTi
. (Note that the default weekly frequency
is "wmonday" (Monday-ending weeks), so latestWeek
always
returns "wmonday" ti
's.) See
setDefaultFrequencies
to change this.
All of the other latest{SomeFreq}
functions work the same way,
returning the ti
's for the most recently completed SomeFreq as
of the last day of xTi
. The tif
's (frequencies) for
latestHalf
and latestQ4
are "semiannual" and
"quarterly", respectively.
latestJanuary
returns the monthly ti
for January of the
most recently completed January-ending year that the last day of its
argument falls into. latestFebruary
returns the monthly
ti
for February of the most recently completed February-ending
year that the last day of its argument falls into, and so on.
All return return ti
objects as described in the details.
ti
, tif
, currentWeek
setDefaultFrequencies
lintegrate
gives the values resulting from integrating a linear
spline, while ilspline
returns linear splines that
integrate to given values.
lintegrate(x, y, xint, stepfun = F, rule = 0) ilspline(xint, w)
lintegrate(x, y, xint, stepfun = F, rule = 0) ilspline(xint, w)
x |
x coordinates of the linear spline F defined by |
y |
y coordinates of the linear spline F defined by |
xint |
x intervals, i.e. |
stepfun |
if |
rule |
one of {0, 1, NA} to specify the behavior of F outside the
range of |
w |
values the linear spline must integrate to |
lintegrate
integrates the linear spline F defined by
(x,y)
over the xint
intervals. The value of F outside
the range of x
is specified by the rule
argument:
rule == 0 --> F(z) = 0 for z outside the range of x rule == NA --> F(z) = NA for z outside the range of x rule == 1 --> F(z) extended for z outside the range of x
If stepfun
is TRUE
, F(z) is assumed to be a
left-continuous step function and the last value of y
is never
accessed.
(x[i], y[i])
pairs with NA values in either x[i] or y[i] NA are
ignored in constructing F.
ilspline
finds linear splines that integrate over the N
intervals specified by the monotonically increasing N+1 vector
xint
to the N values given in w
. The function finds
N-vectors x and y such that:
(i) x[j] = (xint[j-1] + xint[j])/2, i.e., the values of x are the midpoints of the intervals specified by xint, and (ii) the linear spline that passes through the (x[i], y[i]) pairs (and is extended to xint[1] and xint[N+1] by linear extrapolation) integrates over each interval [xint[j],xint[j+1]] to w[j].
In fact, w
can actually be an M by N matrix, in which case the
y found by the function is also an M by N matrix, with each column of
y giving the y coordinates of a linear spline that integrates to the
corresponding column of w
.
lintegrate
returns a vector of length length(xint) - 1
.
ilspline
returns a list with components named 'x' and 'y'.
w <- 10 + cumsum(rnorm(10)) blah <- ilspline(1:11, w) ww <- lintegrate(blah$x, blah$y, 1:11, rule = 1) w - ww ## should be all zeroes (or very close to zero)
w <- 10 + cumsum(rnorm(10)) blah <- ilspline(1:11, w) ww <- lintegrate(blah$x, blah$y, 1:11, rule = 1) w - ww ## should be all zeroes (or very close to zero)
Plotting methods for tis
objects
## S3 method for class 'tis' lines(x, offset = 0.5, dropNA = FALSE, ...) ## S3 method for class 'tis' points(x, offset = 0.5, dropNA = FALSE, ...)
## S3 method for class 'tis' lines(x, offset = 0.5, dropNA = FALSE, ...) ## S3 method for class 'tis' points(x, offset = 0.5, dropNA = FALSE, ...)
x |
a |
offset |
a number in the range [0,1] telling where in each period of |
dropNA |
if |
... |
other arguments to be passed on to |
These are fairly simple wrappers around the lines.default
and
points.default
. For example, lines.tis
basically does this:
lines.default(x = time(x, offset = offset), y = x, ...)
and points.tis
is similar. If dropNA
is TRUE
, the
observations in x
that are NA
are dropped from the x and
y vectors sent to the .default functions. For points
, this
shouldn't matter, since points.tis
omits points with NA
values from the plot.
For lines
the dropNA
parameter does make a difference.
The help document for lines
says:
"The coordinates can contain NA
values. If a point contains
NA
in either its x
or y
value, it is omitted from
the plot, and lines are not drawn to or from such points. Thus
missing values can be used to achieve breaks in lines."
Note that if the type
is one of c("p", "b", "o")
, the
non-NA
points are still drawn, but line segments from those
points to adjacent NA
points are not drawn. If dropNA = TRUE
,
the NA
points are dropped before calling lines.default
,
and all of the remaining points will be connected with line segments
(unless suppressed by the type
argument).
Merge two time-indexed series using either the levels or the first differences of the second series where the series overlap.
mergeSeries(x, y, differences = FALSE, naLoses = FALSE)
mergeSeries(x, y, differences = FALSE, naLoses = FALSE)
x , y
|
|
differences |
if |
naLoses |
if |
x
and y
must have the same tif
(ti frequency),
and the same number of column (if they are multivariate).
A tis
object series with start and end dates that span those of
x
and y
. Where the series overlap, values from y
are used, except that if naLoses
is TRUE
, NA
values from y
do not overwrite non-NA
values in x
.
Windows a tis
or ts
time series to cut off leading and trailing
NA (and optionally zero) observations.
naWindow(x, union = F, zero = F)
naWindow(x, union = F, zero = F)
x |
a |
union |
see details below |
zero |
if |
For multivariate (multiple columns) series and union = TRUE
, a
row of x
is considered to be NA if and only if all entries in
that row are NA. If union = FALSE
(the default), a row is
considered to be NA if any of its entries is NA.
if zero
is TRUE
, the function chops off leading and
trailing observations that are either NA
or zero. Otherwise,
it chops only NA
s.
A copy of x
with leading and trailing NA observations deleted.
nberDates
returns a matrix with two columns of yyyymmdd dates
giving the Start and End dates of recessions fixed by the NBER.
nberShade
is a generic method for shading recession areas
on the current plot. The default version calls
nberDates()
to get a matrix of yyyymmdd dates and then passes
those dates and all other arguments along to ymdShade
.
romerLines
draws vertical lines on the current plot at the
"Romer and Romer" dates when monetary policy is said to have become
contractionary.
## Default S3 method: nberShade(...) nberDates() romerLines()
## Default S3 method: nberShade(...) nberDates() romerLines()
... |
args passed to |
nberDates
returns the two column matrix of recession date
ranges described above.
Nothing useful is returned by the other functions.
Recessions are dated by the Business Cycle Dating Committee of the National Bureau of Economic Research.
The Romer dates are October 1947, September 1955, December 1968, April 1974, August 1978, October 1979 and December 1988.
Christina D. Romer and David H. Romer. 1989. "Does Monetary Policy Matter? A New Test in the Spirit of Friedman and Schwartz." NBER Macroeconomics Annual 4: 121-170.
Christina D. Romer and David H. Romer. 1994. "Monetary Policy Matters." Journal ofMonetary Economics 34 (August): 75-88.
National Bureau of Economic Research. http://www.nber.org.
require("datasets") plot(presidents, type='n', ylab="Presidents approval rating") nberShade() lines(presidents)
require("datasets") plot(presidents, type='n', ylab="Presidents approval rating") nberShade() lines(presidents)
This is a shortcut call to plot.window
that has some
of the parameters set to different defaults than the usual values.
plotWindow(xlim, ylim, log = "", asp = NA, xaxs = "i", yaxs = "i", ...)
plotWindow(xlim, ylim, log = "", asp = NA, xaxs = "i", yaxs = "i", ...)
xlim , ylim
|
numeric of length 2, giving the x and y coordinates ranges. |
log |
character; indicating which axes should be in log scale. |
asp |
numeric, giving the aspect ratio y/x. |
xaxs |
style of axis interval calculation for the x-axis |
yaxs |
style of axis interval calculation for the y-axis |
... |
further graphical parameters as in |
Functions to create objects of classes "POSIXlt"
and
"POSIXct"
representing calendar dates and times.
POSIXct(x, ...) POSIXlt(x, ...) ## S3 method for class 'jul' as.POSIXct(x, tz = "", ...) ## S3 method for class 'ti' as.POSIXct(x, tz = "", offset = 1, ...) ## S3 method for class 'jul' POSIXct(x, ...) ## S3 method for class 'numeric' POSIXct(x, tz = "", origin, ...) ## S3 method for class 'ti' POSIXct(x, offset = 1, ...) ## Default S3 method: POSIXct(x, ...) ## S3 method for class 'jul' POSIXlt(x, ...) ## S3 method for class 'ti' POSIXlt(x, ...) ## Default S3 method: POSIXlt(x, ...)
POSIXct(x, ...) POSIXlt(x, ...) ## S3 method for class 'jul' as.POSIXct(x, tz = "", ...) ## S3 method for class 'ti' as.POSIXct(x, tz = "", offset = 1, ...) ## S3 method for class 'jul' POSIXct(x, ...) ## S3 method for class 'numeric' POSIXct(x, tz = "", origin, ...) ## S3 method for class 'ti' POSIXct(x, offset = 1, ...) ## Default S3 method: POSIXct(x, ...) ## S3 method for class 'jul' POSIXlt(x, ...) ## S3 method for class 'ti' POSIXlt(x, ...) ## Default S3 method: POSIXlt(x, ...)
x |
An object to be converted. |
tz |
A timezone specification to be used for the conversion,
if one is required. System-specific (see time zones),
but |
origin |
a date-time object, or something which can be coerced by
|
offset |
a number between 0 and 1 specifying where in the period
represented by the |
... |
other args passed to |
The default methods POSIXct.default
and POSIXlt.default
do nothing but call as.POSIXct
and as.POSIXlt
,
respectively. The POSIXct.ti
method can take an offset
argument as explained above, and the POSIXct.jul
method can
handle jul
objects with a fractional part. The ti
and
jul
methods for POSIXlt
just call the POSIXct
constructor and then convert it's value to a POSIXlt
object.
as.POSIXct
, POSIXct
and POSIXlt
return objects of the
appropriate class. If tz
was specified it will be reflected in
the "tzone" attribute of the result.
as.POSIXct
and link{as.POSIXlt}
for the default
conversion functions, and DateTimeClasses for details of the
classes.
Print method for time index.
## S3 method for class 'ti' print(x, class = TRUE, ...)
## S3 method for class 'ti' print(x, class = TRUE, ...)
x |
a time index |
class |
if( |
... |
additional arguments that may be passed along to generic |
This simply calls
print(as.character(x), quote = FALSE, ...)
.
print(today(), class = FALSE) ## compare to today()
print(today(), class = FALSE) ## compare to today()
Print method for time indexed series.
## S3 method for class 'tis' print(x, format = "%Y%m%d", matrix.format = FALSE, class = TRUE, ...)
## S3 method for class 'tis' print(x, format = "%Y%m%d", matrix.format = FALSE, class = TRUE, ...)
x |
a time indexed series |
format |
a character string describing how to format the observation times if
either |
matrix.format |
|
class |
if( |
... |
additional arguments that may be passed along to |
If matrix.format
is F
(the default) and x
is
a univariate monthly, quarterly or annual series, printing is
accomplished by print(as.ts(x), ...)
. Otherwise,
x
is printed as a matrix with rownames created by
formatting the time indexes of the observations according to the
format
string.
print(tis(1:31, start = today() - 30), format = "%b %d, %Y")
print(tis(1:31, start = today() - 30), format = "%b %d, %Y")
Form row sums and means for numeric arrays.
RowSums (x, ...) RowMeans(x, ...) ## Default S3 method: RowSums(x, ...) ## Default S3 method: RowMeans(x, ...) ## S3 method for class 'tis' RowSums(x, ...) ## S3 method for class 'tis' RowMeans(x, ...)
RowSums (x, ...) RowMeans(x, ...) ## Default S3 method: RowSums(x, ...) ## Default S3 method: RowMeans(x, ...) ## S3 method for class 'tis' RowSums(x, ...) ## S3 method for class 'tis' RowMeans(x, ...)
x |
an array of two or more dimensions, containing numeric,
complex, integer or logical values, or a numeric data frame, or a
|
... |
arguments passed along to |
The tis
-specific methods return a tis
.
For other types of x
, see rowMeans
or rowSums
.
mat <- tis(matrix(1:36, ncol = 3), start = latestJanuary()) cbind(mat, rowSums(mat), rowMeans(mat))
mat <- tis(matrix(1:36, ncol = 3), start = latestJanuary()) cbind(mat, rowSums(mat), rowMeans(mat))
Plotting function with scads of options for creating high quality scatter
plots. Can be used with screenPage
.
scatterPlot(x, y, plotType = "p", lineType = "solid", lineWidth = 1.5, plotChar = "*", dataCex = 1, color = "black", xAxisMin = NULL, xAxisMax = NULL, xExpandBy = 0.04, xTicks = 5, xTickLocations = NULL, labelXTicks = TRUE, xTickLabels = NULL, xCex = 1, xAxisLabel = NULL, labelXAxis = TRUE, xSpace = 4, yAxisMin = NULL, yAxisMax = NULL, yExpandBy = 0.04, yTicks = 5, yTickLocations = NULL, yTickLabels = NULL, labelLeftTicks = FALSE, labelRightTicks = TRUE, yCex = 1, extendTopTick = TRUE, leftAxisLabel = NULL, rightAxisLabel = NULL, labelLeftAxis = TRUE, labelRightAxis = FALSE, cex = 1, head = NULL, headAlign = 0.5, headCex = 1.5, sub = NULL, subCex = 0.85, leftTopLabel = NULL, rightTopLabel = NULL, topLabelAlign = 0, labCex = 1, leftInsideLabel = NULL, rightInsideLabel = NULL, innerOffset = 0.05, innerCex = 0.8, foot = NULL, footAlign = 0, footCex = 0.8, footSpace = -1, tck = 0.03, axisWidth = 2, boxType = "u", leftMargin = -1, rightMargin = -1, topMargin = -1, bottomMargin = -1)
scatterPlot(x, y, plotType = "p", lineType = "solid", lineWidth = 1.5, plotChar = "*", dataCex = 1, color = "black", xAxisMin = NULL, xAxisMax = NULL, xExpandBy = 0.04, xTicks = 5, xTickLocations = NULL, labelXTicks = TRUE, xTickLabels = NULL, xCex = 1, xAxisLabel = NULL, labelXAxis = TRUE, xSpace = 4, yAxisMin = NULL, yAxisMax = NULL, yExpandBy = 0.04, yTicks = 5, yTickLocations = NULL, yTickLabels = NULL, labelLeftTicks = FALSE, labelRightTicks = TRUE, yCex = 1, extendTopTick = TRUE, leftAxisLabel = NULL, rightAxisLabel = NULL, labelLeftAxis = TRUE, labelRightAxis = FALSE, cex = 1, head = NULL, headAlign = 0.5, headCex = 1.5, sub = NULL, subCex = 0.85, leftTopLabel = NULL, rightTopLabel = NULL, topLabelAlign = 0, labCex = 1, leftInsideLabel = NULL, rightInsideLabel = NULL, innerOffset = 0.05, innerCex = 0.8, foot = NULL, footAlign = 0, footCex = 0.8, footSpace = -1, tck = 0.03, axisWidth = 2, boxType = "u", leftMargin = -1, rightMargin = -1, topMargin = -1, bottomMargin = -1)
x |
the x coordinates of points in the plot. If this is a string, the
function |
y |
the y coordinates of points in the plot. If this is a string, the
function |
plotType |
type of plot desired. Values are |
lineType |
character or numeric vector specifying the line type if
|
lineWidth |
default is |
plotChar |
character (or number for plotting symbols – see the help for
|
dataCex |
|
color |
string or number. Default is 1, the device default foreground color. |
xAxisMin |
minimum value of the x axis. If non-NULL, this overrides the
calculation described in |
xAxisMax |
maximum value of the x axis. If non-NULL, this overrides the
calculation described in |
xExpandBy |
a single number or two numbers between 0 and 1. |
xTicks |
number of ticks to draw on x axis at "pretty" locations. Default
is 5. This argument is ignored if |
xTickLocations |
if non-NULL, a vector of desired tick locations or a string that
evaluates to such a vector. The default value NULL lets the setting
for |
labelXTicks |
If |
xTickLabels |
character vector of tick labels or NULL (the default). If NULL and
|
xCex |
|
xAxisLabel |
text to appear centered under the x axis. Default value NULL creates
a string by deparsing the |
labelXAxis |
if |
xSpace |
lines of space to set aside directly beneath the x-axis to hold
tick, year and/or axis labels. Default is |
yAxisMin |
minimum value of the y axis. If non-NULL, this overrides the
calculation described in |
yAxisMax |
maximum value of the y axis. If non-NULL, this overrides the
calculation described in |
yExpandBy |
a single number or two numbers between 0 and 1. |
yTicks |
number of ticks to draw on y axis at "pretty" locations. Default
is 5. This argument is ignored if |
yTickLocations |
if non-NULL, a vector of desired tick locations or a string that
evaluates to such a vector. The default value NULL lets the setting
for |
yTickLabels |
character vector of tick labels or NULL (the default). If NULL and
|
labelLeftTicks |
If |
labelRightTicks |
If |
yCex |
|
extendTopTick |
if |
leftAxisLabel |
text to appear centered outside the left axis.
Default value NULL creates a string by deparsing the |
labelLeftAxis |
if |
rightAxisLabel |
text to appear centered outside the right axis.
Default value NULL creates a string by deparsing the |
labelRightAxis |
if |
cex |
the base character expansion factor by which all of the
|
head |
text to appear at the top of the figure region, with alignment
determined by |
headAlign |
number indicating justification for the strings in |
headCex |
|
sub |
text to appear just under |
subCex |
|
leftTopLabel |
text to appear at the top of the left axis, with alignment
determined by |
rightTopLabel |
text to appear at the top of the right axis, with alignment
determined by |
topLabelAlign |
number indicating alignment for the strings in |
labCex |
|
leftInsideLabel |
text to appear left justified and just inside the upper left corner of the plot region. No default. |
rightInsideLabel |
text to appear right justified and just inside the upper right corner of the plot region. No default. |
innerOffset |
number between 0 and 1, a fractional offset for the inside labels.
The left edge of |
innerCex |
|
foot |
text to appear at the bottom of the figure region, with alignment
determined by |
footAlign |
number indicating justification for the strings in |
footCex |
|
footSpace |
lines of space to set aside directly beneath the space allocated by
|
tck |
length of major tick marks in inches. Minor ticks are 2/3 as long. Default is 0.03. |
axisWidth |
line width for the axes and box (if any). Default is 2. |
boxType |
character representing the type of box. Characters |
leftMargin |
lines of space for the left margin. Default value (-1) figures this out automatically. |
rightMargin |
lines of space for the right margin. Default value (-1) figures this out automatically. |
topMargin |
lines of space for the top margin. Default value (-1) figures this out automatically. |
bottomMargin |
lines of space for the bottom margin. Default value (-1) figures this out automatically. |
Each of the text items head
, sub
, leftTopLabel
,
rightTopLabel
, leftInsideLabel
, rightInsideLabel
,
foot
, leftAxisLabel
, rightAxisLabel
and
xAxisLabel
can be given as a string, a collections of strings,
or as a string that gets evaluated to one of the first two. Multiple
strings are drawn on successive lines.
scatterPlot
invisibly returns a list of class "scatterPlot" and
elements named xy
(a matrix containing x
and y
in
two columns), plotType
, lineType
, color
,
plotChar
, lineWidth
, x
(x coordinate for legend),
y
(y coordinate for legend), xRange
, yRange
,
innerCex
and par
.
This list is useful mostly as an argument to legend
.
scatterPlot
is a companion to tisPlot
. Both are
designed to be driven from a graphical user interface.
Places header and footer text items in outer margin of page and splits the screen appropriately. Can also redraw header and footer.
screenPage(head = NULL, sub = NULL, foot = NULL, date = FALSE, dateFormat = "%x", time = FALSE, topLeft = character(0), topRight = character(0), headFont = par("font.main"), subFont = par("font.sub"), footFont = par("font"), cex = 1.001, headCex = 1.5, subCex = 0.85, footCex = 0.75, topLeftCex = 0.85, topRightCex = 0.85, footAlign = 0, leftMargin = 0, rightMargin = leftMargin, topMargin = 0, bottomMargin = topMargin)
screenPage(head = NULL, sub = NULL, foot = NULL, date = FALSE, dateFormat = "%x", time = FALSE, topLeft = character(0), topRight = character(0), headFont = par("font.main"), subFont = par("font.sub"), footFont = par("font"), cex = 1.001, headCex = 1.5, subCex = 0.85, footCex = 0.75, topLeftCex = 0.85, topRightCex = 0.85, footAlign = 0, leftMargin = 0, rightMargin = leftMargin, topMargin = 0, bottomMargin = topMargin)
head |
character string or strings to appear centered in the top outer margin
of the page. If |
sub |
character string or strings to appear centered just under |
foot |
character string or strings to appear in the bottom outer margin of the page. |
date |
logical: if |
dateFormat |
|
time |
logical: if |
topLeft |
character string or strings to appear at top left corner of the page |
topRight |
character string or strings to appear at top right corner of the page |
headFont |
font to use in writing the main title in |
subFont |
font to use in writing the sub title in |
footFont |
font to use in writing the footnotes in |
cex |
number by which all of the other "cex" arguments are scaled. |
headCex |
number: Character Expansion Factor (cex) for the string(s) in
|
subCex |
number: cex for the string(s) in |
footCex |
number: cex for the string(s) in |
topLeftCex |
number: cex for the string(s) appearing in the top left corner
of the page. The actual cex used for these strings will be
|
topRightCex |
number: cex for the string(s) appearing in the top right corner
of the page, including the time and date stamps.
The actual cex used for these strings will be |
footAlign |
number: justification for the strings in |
leftMargin |
left margin of page in inches. |
rightMargin |
right margin of page in inches. Default is same
as |
topMargin |
top margin of page in inches. |
bottomMargin |
bottom margin of page in inches. Default is same
as |
screenPage
first sets aside space for the margins specified by
topMargin
, bottomMargin
, leftMargin
and
rightMargin
. Then it figures out how much additional space is
needed for the top and bottom outer margin text elements, places them,
and then splits the screen in 3, with screen 3 being the middle part
of the page. The user is then free either to further subdivide screen
3 (using split.screen()
) or to use it as is.
On exit, screen 3 is the active screen.
This function returns a list of all of its arguments, including default values for arguments that were not supplied. The return is invisible if a graphics device is active.
screenPage(head = "Chart 1", date = TRUE, foot = rep(" ", 4), cex = 0.85, headCex = 1) ## then draw charts, possibly after further subdividing the screen
screenPage(head = "Chart 1", date = TRUE, foot = rep(" ", 4), cex = 0.85, headCex = 1) ## then draw charts, possibly after further subdividing the screen
Sets the color palette (used when a col=
has a
numeric index) to a given vector of colors
, and also sets the
graphics parameters (see par
) col
,
col.axis
, col.lab
, col.main
, col.sub
and
fg
to colors[1]
.
setColors(colors)
setColors(colors)
colors |
a character vector |
The new color palette.
A tif
(Time Index Frequency) can usually be set
either by code (a number) or by name. setDefaultFrequencies
sets particular frequencies for the tif
names "weekly",
"biweekly", "bimonthly" (also "bimonth"), "quarterly" (also "q"),
"annual" (also "a"), and "semiannual" (also "sann").
tifList
returns the map of frequency names to frequency codes.
setDefaultFrequencies(weekly = "wmonday", biweekly = "bw1wednesday", bimonthly = "bimonthdecember", quarterly = "qdecember", annual = "anndecember", semiannual = "sanndecember", setup = FALSE) tifList()
setDefaultFrequencies(weekly = "wmonday", biweekly = "bw1wednesday", bimonthly = "bimonthdecember", quarterly = "qdecember", annual = "anndecember", semiannual = "sanndecember", setup = FALSE) tifList()
weekly |
A string giving the name of the particular frequency that frequency "weekly" will correspond to |
biweekly |
Ditto for "biweekly" |
bimonthly |
Ditto for "bimonth" and "bimonthly" |
quarterly |
Ditto for "q" and "quarterly" |
annual |
Ditto for "a" and "annual" |
semiannual |
Ditto for "sann" and "semiannual" |
setup |
If |
The named vector .tifList
(returned by the function of
the same name) stored in the global enviroment contains the mapping of
frequency names to frequency codes. Running this function modifies
the tifList
vector and stores it back in the global environment.
It gets run with setup = TRUE
when the tis
package is loaded.
If you want different defaults, call the function sometime after that.
A copy of the .tifList
vector.
This function solves the equation a %*% x = b
for x
,
where a
is tridiagonal and b
can be either a vector or a
matrix.
## S3 method for class 'tridiag' solve(a, b, ...)
## S3 method for class 'tridiag' solve(a, b, ...)
a |
a |
b |
a vector or matrix giving the right-hand side(s) of the
linear system. If missing, |
... |
ignored |
Uses the LINPACK dgtsv
routine.
The function ssDate
is used to create ssDate
(spreadsheet date) objects, which are useful for reading and writing
dates in spreadsheet form, i.e., as the number of days since December
30, 1899.
as.ssDate
and is.ssDate
coerce an object to a ssDate and
test whether an object is a ssDate
.
ssDate(x, ...) as.ssDate(x) is.ssDate(x)
ssDate(x, ...) as.ssDate(x) is.ssDate(x)
x |
object to be tested ( |
... |
other args to be passed to |
an ssDate
is essentially a rebased Julian date that represents
a date as the number of days since December 30, 1899. The
constructor function ssDate
subtracts jul(18991230)
from
jul(x, ...)
and coerces the result to class ssDate
.
Pretty much all of the stuff you can do with jul
objects can
also be done with ssDate
objects.
is.ssDate
returns TRUE
or FALSE
.
as.ssDate
coerces its argument to have class ssDate
, without
making any attempt to discern whether or not this is a sensible thing
to do.
ssDate
constructs a ssDate
object like x
.
ssDate
with no arguments returns the ssDate
for the current day.
dec31 <- ssDate(20041231) jan30 <- ssDate("2005-1-30") jan30 - dec31 ## 30 feb28 <- jan30 + 29 ssDate() ## current date
dec31 <- ssDate(20041231) jan30 <- ssDate("2005-1-30") jan30 - dec31 ## 30 feb28 <- jan30 + 29 ssDate() ## current date
Return the start or end time index for a tis
object.
## S3 method for class 'tis' start(x, ...) ## S3 method for class 'tis' end(x, ...) start(x) <- value
## S3 method for class 'tis' start(x, ...) ## S3 method for class 'tis' end(x, ...) start(x) <- value
x |
a |
value |
desired |
... |
ignored |
start.tis
returns the start
attribute of x
, while
end.tis
returns start(x) + nobs(x) - 1
.
start(x) <- value
returns the series x
shifted such that
it's starting time is value
.
start
and end
are generic functions with default methods
that assume x
has (or can be given) a tsp
attribute.
The default methods return a two vector as c(year, period), while the
methods described here return infinitely more useful ti
objects.
x <- tis(numeric(8), start = c(2001, 1), freq = 4) start(x) ## --> ti object representing 2001Q1 start(as.ts(x)) ## --> c(2001, 1)
x <- tis(numeric(8), start = c(2001, 1), freq = 4) start(x) ## --> ti object representing 2001Q1 start(as.ts(x)) ## --> c(2001, 1)
Strips leading and trailing blanks from strings
stripBlanks(strings)
stripBlanks(strings)
strings |
character vector |
An object like strings
with no leading or trailing blanks.
An R object may have a class attribute that is a character
vector giving the names of classes it inherits from. stripClass
strips the class classString
from that character vector.
stripTis(x)
is shorthand for stripClass(x, "tis")
.
stripClass(x, classString) stripTis(x)
stripClass(x, classString) stripTis(x)
x |
an object whose |
classString |
name of class to remove from the inheritance chain |
An object like x
, but whose class
attribute does
not include classString
. If the class
attribute less
classString
is empty, unclass(x)
is returned.
This function can be useful in functions that return a modified
version of one their arguments. For example, the format.ti
method
takes a ti
(TimeIndex) as an argument and returns a character object
object 'like' the original argument. The first thing
format.ti(x)
does internally is z <- stripClass(x, "ti")
.
This creates z
as a copy of x
but with the difference
that z
no longer inherits from class ti
. The function
then fills in the data elements of z
with the approriate
strings and returns it. The beauty of this approach is that the
returned z
already has all of the attributes x
had,
except that it no longer inherits from class ti
. In
particular, if x
was a matrix with dimnames, etc., z
will also have those attributes.
Returns the transpose of as.matrix(x)
## S3 method for class 'tis' t(x)
## S3 method for class 'tis' t(x)
x |
a |
A matrix, see t
. Note that this is not a
time series.
a <- tis(matrix(1:30, 5,6), start = latestMonth()) a t(a) ##i.e., a[i, j] == t(a)[j, i] for all i,j, and t(a) is NOT a time series
a <- tis(matrix(1:30, 5,6), start = latestMonth()) a t(a) ##i.e., a[i, j] == t(a)[j, i] for all i,j, and t(a) is NOT a time series
The function ti
is used to create time index objects, which are
useful for date calculations and as indexes for tis
(time
indexed series).
as.ti
and asTi
coerce an object to a time index, the
difference being that as.ti
calls the constructor ti
,
while asTi
simply forces the class of its argument to be "ti"
without any checking as to whether or not it makes sense to do so.
is.ti
tests whether an object is a time index.
couldBeTi
tests whether or not x
is numeric and has all
elements within the range expected for a ti
time index with the
given tif
. If tif
is NULL
(the default), the test
is whether or not x
could be a ti
of any
frequency. If so, it can be safely coerced to class ti
by
as.ti
.
ti(x, ...) ## S3 method for class 'Date' ti(x, ...) ## Default S3 method: ti(x, tif = NULL, freq = NULL, ...) ## S3 method for class 'jul' ti(x, tif = NULL, freq = NULL, hour = 0, minute = 0, second = 0, ...) ## S3 method for class 'ssDate' ti(x, ...) ## S3 method for class 'ti' ti(x, tif = NULL, freq = NULL, ...) ## S3 method for class 'tis' ti(x, ...) ## S3 method for class 'yearmon' ti(x, ...) ## S3 method for class 'yearqtr' ti(x, ...) as.ti(x, ...) asTi(x) is.ti(x) couldBeTi(x, tif = NULL)
ti(x, ...) ## S3 method for class 'Date' ti(x, ...) ## Default S3 method: ti(x, tif = NULL, freq = NULL, ...) ## S3 method for class 'jul' ti(x, tif = NULL, freq = NULL, hour = 0, minute = 0, second = 0, ...) ## S3 method for class 'ssDate' ti(x, ...) ## S3 method for class 'ti' ti(x, tif = NULL, freq = NULL, ...) ## S3 method for class 'tis' ti(x, ...) ## S3 method for class 'yearmon' ti(x, ...) ## S3 method for class 'yearqtr' ti(x, ...) as.ti(x, ...) asTi(x) is.ti(x) couldBeTi(x, tif = NULL)
x |
object to be tested ( |
hour |
used if and only if |
minute |
used if and only if |
second |
used if and only if |
... |
other args to be passed to the method called by the generic function. |
tif |
a ti Frequency, given as either a numerical code or a string.
|
freq |
some |
A ti
has a tif
(ti Frequency) and a period. The period
represents the number of periods elapsed since the base period for that
frequency. Adding or subtracting an integer to a ti
gives
another ti
. Provided their corresponding element have matching
tif
s, the comparison operators <, >, <=, >=, ==
all
work, and subtracting one ti
from another gives the number of
periods between them. See the examples section below.
The ti
class implements methods for a number of generic
functions, including "["
, as.Date
, as.POSIXct
,
as.POSIXlt
, c
, cycle
, edit
, format
,
frequency
, jul
, max
, min
, print
,
rep
, seq
, tif
, tifName
, time
,
ymd
.
ti
is a generic function with specialized methods to handle
jul
, Date
, ti
. tis
, yearmon
and
yearqtr
objects.
The default method (ti.default
) deals with character x
by
calling as.Date
on it. Otherwise, it proceeds as follows:
If x
is numeric, a check is made to see if x
could be
a ti
object that has somehow lost it's class attribute. Failing that,
isYmd
is used to see if it could be yyyymmdd date, then
isTime
is called to see if x
could be a decimal time (a
number between 1799 and 2200). If x
is of length 2, an attempt
to interpret it as a c(year, period)
pair is made. Finally,
if all else fails, as.Date(x)
is called to attempt to create a
Date
object that can then be used to construct a ti
.
is.ti
and couldBeTi
return TRUE
or FALSE
.
as.ti
returns a ti
object.
asTi
returns its argument with the class attribute set to "ti".
ti
constructs a ti
object like x
, except for two
special cases:
1. If x
is a tis
series, the return value is a vector
time index with elements corresponding to the observation periods of
x
.
2. If x
is a numeric object of length 2 interpretable as
c(year, period)
, the return value is a single ti
.
The as.Date(x)
call is not wrapped in a try-block, so it may be at
the top of the stack when ti
fails.
The return value from asTi
is not guaranteed to be a valid
ti
object. For example, asTi("a")
will not throw an
error, and it will return the string "a" with a class attribute "ti",
but that's not a valid time index.
jul
, ymd
, tif
,
tifName
, as.Date
z <- ti(19971231, "monthly") ## monthly ti for Dec 97 is.ti(z) ## TRUE is.ti(unclass(z)) ## FALSE couldBeTi(unclass(z)) ## TRUE ymd(z + 4) ## 19980430 z - ti(c(1997,6), freq = 12) ## monthly ti for June 1997 ti(z, tif = "wmonday") ## week ending Monday June 30, 1997
z <- ti(19971231, "monthly") ## monthly ti for Dec 97 is.ti(z) ## TRUE is.ti(unclass(z)) ## FALSE couldBeTi(unclass(z)) ## TRUE ymd(z + 4) ## 19980430 z - ti(c(1997,6), freq = 12) ## monthly ti for June 1997 ti(z, tif = "wmonday") ## week ending Monday June 30, 1997
Return a daily or business day ti
corresponding to a
specified position within a time index.
tiDaily(xTi, offset = 1) tiBusiness(xTi, offset = 1)
tiDaily(xTi, offset = 1) tiBusiness(xTi, offset = 1)
xTi |
a |
offset |
for |
tiDaily
converts its first argument to a jul
using the
offset provided, and returns a daily ti
for that day.
tiBusiness
converts its first argument to a jul
using the
offset provided, and returns a "business" ti
for that day.
A tier chart plots several years' observations of a series against the times of year in which they were observed. Useful for seeing seasonal patterns in daily, weekly and irregularly-spaced data.
tierChart(x, startMonth = latestJanuary(end(x)), nMonths = 4, nYears = 7, offsets = 0, padDays = 6, pch = "year", lty = "solid", lwd = 1.5, col = 1 + (n.y:1), type = "b", ylim = NULL, outlier.trim = 0, noTrimLastYear = TRUE, extendHorizontalTicks = TRUE, circles.ymd = NULL, circles.col = 6, circles.inches = 0.1, vlines.ymd = NULL, vlines.col = 2, vlines.lty = 4, vlines.lwd = 1.5, vlines2.ymd = NULL, vlines2.col = 3, vlines2.lty = "solid", vlines2.lwd = 2, hlines = NULL, hlines.col = 1, hlines.lty = 1, hlines.lwd = 1, tiPoints.1 = NULL, tiPoints.2 = NULL, pch.1 = "*", pch.2 = "+", col.1 = 2, col.2 = 3, nolegend = FALSE, main = deparse(substitute(x)), topleft.labels = NULL, topright.labels = NULL, legend.ncol = length(years), legend.bg = 0, timestamp = TRUE, topline = TRUE, vlines.periodEnd = TRUE, vlines.month = TRUE, midperiod = FALSE, lwdLastYear = 1.5, cex = 1.5, boxes = TRUE, ...) adjustableTierChart(x, ..., edit = TRUE, changes = numeric(0), verbose = FALSE)
tierChart(x, startMonth = latestJanuary(end(x)), nMonths = 4, nYears = 7, offsets = 0, padDays = 6, pch = "year", lty = "solid", lwd = 1.5, col = 1 + (n.y:1), type = "b", ylim = NULL, outlier.trim = 0, noTrimLastYear = TRUE, extendHorizontalTicks = TRUE, circles.ymd = NULL, circles.col = 6, circles.inches = 0.1, vlines.ymd = NULL, vlines.col = 2, vlines.lty = 4, vlines.lwd = 1.5, vlines2.ymd = NULL, vlines2.col = 3, vlines2.lty = "solid", vlines2.lwd = 2, hlines = NULL, hlines.col = 1, hlines.lty = 1, hlines.lwd = 1, tiPoints.1 = NULL, tiPoints.2 = NULL, pch.1 = "*", pch.2 = "+", col.1 = 2, col.2 = 3, nolegend = FALSE, main = deparse(substitute(x)), topleft.labels = NULL, topright.labels = NULL, legend.ncol = length(years), legend.bg = 0, timestamp = TRUE, topline = TRUE, vlines.periodEnd = TRUE, vlines.month = TRUE, midperiod = FALSE, lwdLastYear = 1.5, cex = 1.5, boxes = TRUE, ...) adjustableTierChart(x, ..., edit = TRUE, changes = numeric(0), verbose = FALSE)
x |
A monhly or higher frequency (such as weekly or daily) time indexed
series (a |
startMonth |
a monthly time index ( |
nMonths |
number of months to show on plot. |
nYears |
number of years to include in the plot. |
offsets |
vector of day offsets for the years in descending order. If
|
padDays |
number of extra days to plot before and after the requested months. |
pch |
plotting symbols to be drawn when plotting points. If pch is a
character string, such as "a1b2", the first year's points will be
labeled "a", the second year's with "1", the third with "b", and so
on. Alternatively, pch can be a numeric vector giving the numbers of
plotting symbols to use, as detailed in the documentation for
|
lty |
vector of line types. The first element is for the first year, the second element for the second year, etc., even if lines are not plotted for all years. Line types will be used cyclically until all years are drawn. |
lwd |
number specifying line width |
col |
vector of colors for the years, specified as numbers or color names. |
type |
character string, telling which type of plot
( |
ylim |
ylim is a vector of 2 numbers giving desired y-axis limits. The
actual limits on the plot will be the result of |
outlier.trim |
see |
noTrimLastYear |
if |
extendHorizontalTicks |
if |
circles.ymd |
draws circles around the plotted points corresponding to these ymd
dates. The colors and sizes of the circles are given by
|
circles.col |
see |
circles.inches |
see |
vlines.ymd |
numeric vector of yyyymmdd dates, draws vertical lines of type
|
vlines.col |
see |
vlines.lty |
see |
vlines.lwd |
see |
vlines2.ymd |
numeric vector of yyyymmdd dates, draws vertical lines of type
|
vlines2.col |
see |
vlines2.lty |
see |
vlines2.lwd |
see |
hlines |
numeric vector, draws horizontal lines of type |
hlines.col |
see |
hlines.lty |
see |
hlines.lwd |
see |
tiPoints.1 |
a |
pch.1 |
see |
col.1 |
see |
tiPoints.2 |
a |
pch.2 |
see |
col.2 |
see |
nolegend |
if |
main |
character string giving main title for the chart. |
topleft.labels |
strings to place in left corner of top margin |
topright.labels |
strings to place in right corner of top margin |
legend.ncol |
number of columns to use for legend. Has no effect if
|
legend.bg |
background color for legend |
timestamp |
if |
topline |
if |
vlines.periodEnd |
if |
vlines.month |
if |
midperiod |
if |
lwdLastYear |
line width for the last year plotted. |
boxes |
if |
cex |
numeric character expansion factor for the characters denoting the points on the plot. |
... |
for |
edit |
if |
changes |
used internally by the function to remember what points have been moved thus far while scrolling. This argument should never be set by the user. |
verbose |
if |
A tier chart shows seasonal patterns in data by superimposing the data from the same months of several years onto a single plot. Tier charts can be used both to present a view of a time series and to graphically edit its values by pointing and clicking.
For most purposes, adjustableTierChart
is preferred to
tierChart
, since the former presents a chart that can be
edited, scrolled and printed via mouse clicks, while the latter simply
draws a single chart and returns. However, adjustableTierChart
requires user interaction, which may make it unsuitable for some uses.
When adjustableTierChart
is called, it draws on the current
graphics device and then waits for mouse clicks to occur. A left mouse
button click on one of the scroll arrows changes the display to show
adjacent months, while a left mouse click on the PrintMe box
causes the current plot to be copied to the printer. Left mouse clicks
in the data area of the plot are used to edit the values of the time
series. Arrows are drawn from the current data points to the mouse
location to show where the new data values will be.
A middle mouse button click causes adjustableTierChart
to
return. Closing the graphics window via the windowing system (e.g.,
clicking on the window's X button) has the same effect.
Until adjustableTierChart
is told to return, the entire R
process will appear to be frozen. It isn't actually frozen, it's just
waiting for mouse input. Use tierChart
instead if no user
interaction is desired.
tierChart
invisibly returns a list with the following components:
px |
a matrix with |
py |
a matrix with |
ymd |
matrix of yyyymmdd dates corresponding to x coordinates in |
index |
matrix giving positions of the elements of the y matrix in the original x series, that is, x[index[i,j]] == y[i,j] |
lBox |
vector of 4 numbers giving the c(left, bottom, right, top) bounds of the scroll arrow box in the upper left corner of the plot. |
rBox |
vector of 4 numbers giving the c(left, bottom, right, top) bounds of the scroll arrow box in the upper right corner of the plot. |
printBox |
vector of 4 numbers giving the c(left, bottom, right, top) bounds of the print box in the adjoining the left scroll box. |
startMonth |
the input argument of the same name |
nMonths |
number of months wide the plot is |
nYears |
number of years plotted |
If the input argument codeboxes is F
, the lBox
,
rBox
and printBox
elements of the list will not be
present.
adjustableTierChart
returns the edited input series x
as
a tis
object, with an additional startMonth
attribute.
a tier chart is drawn on the current graphics device.
monthplot
for a nice way to look at seaonality in monthly
data.
## Not run: tierChart(m1.w) ## January - April of 7 most recent years tierChart(m1.w, startMonth=1, nMonths = 12) ## Tier chart for entire year tierChart(m1.w, type="l", lty=1) ## same as first example, but with ## solid lines and no plotting symbols xe <- adjustableTierChart(x) ## xe will be edited version of x ## End(Not run)
## Not run: tierChart(m1.w) ## January - April of 7 most recent years tierChart(m1.w, startMonth=1, nMonths = 12) ## Tier chart for entire year tierChart(m1.w, type="l", lty=1) ## same as first example, but with ## solid lines and no plotting symbols xe <- adjustableTierChart(x) ## xe will be edited version of x ## End(Not run)
Return the tif code of an object, the name associated with a tif code, the period number of a time index, or the first .
tif(x, ...) ## S3 method for class 'ti' tif(x, ...) ## S3 method for class 'tis' tif(x, ...) ## S3 method for class 'ts' tif(x, ...) ## Default S3 method: tif(x, freq = NULL, ...) tifName(s) ## Default S3 method: tifName(s) ## S3 method for class 'ti' tifName(s) ## S3 method for class 'tis' tifName(s) period(z) basePeriod(x)
tif(x, ...) ## S3 method for class 'ti' tif(x, ...) ## S3 method for class 'tis' tif(x, ...) ## S3 method for class 'ts' tif(x, ...) ## Default S3 method: tif(x, freq = NULL, ...) tifName(s) ## Default S3 method: tifName(s) ## S3 method for class 'ti' tifName(s) ## S3 method for class 'tis' tifName(s) period(z) basePeriod(x)
x |
a |
freq |
numeric. If |
... |
ignored |
s |
a |
z |
a |
The tifList
object associates tifNames with tif codes. Most
functions that call for tif
argument can take either a tif code
or a tif name.
Both function are generic function with methods for ti
and
tis
objects, as well as a default method. tif
also has
a method for ts
objects.
tif
returns the tif code for x
, while tifName
returns a name for that code. Many of the codes have several names,
but only the default one is returned.
tif
or tifName
called with no arguments returns a vector
of all tif codes with names.
period
returns a vector like z
giving the number of
periods elapsed since the first period defined for its argument's
frequency.
basePeriod
returns the ti
for the first period defined
for tif(x)
.
tif() ## returns a vector of all tif codes tifName(today()) ## today() returns a ti period(today())
tif() ## returns a vector of all tif codes tifName(today()) ## today() returns a ti period(today())
Returns the frequency of a ti
object constructed from the
current date with the given tif
.
tif2freq(tif)
tif2freq(tif)
tif |
a |
a number
tif2freq("wmonday") tif2freq("monthly") tif2freq(tif(today()))
tif2freq("wmonday") tif2freq("monthly") tif2freq(tif(today()))
The function tis
is used to create time-indexed series objects.
as.tis
and is.tis
coerce an object to a time-indexed
series and test whether an object is a time-indexed series.
tis(data, start = 1, tif = NULL, frequency = NULL, end = NULL) as.tis(x, ...) ## S3 method for class 'ts' as.tis(x, ...) ## S3 method for class 'tis' as.tis(x, ...) ## S3 method for class 'zoo' as.tis(x, ...) ## Default S3 method: as.tis(x, ...) is.tis(x)
tis(data, start = 1, tif = NULL, frequency = NULL, end = NULL) as.tis(x, ...) ## S3 method for class 'ts' as.tis(x, ...) ## S3 method for class 'tis' as.tis(x, ...) ## S3 method for class 'zoo' as.tis(x, ...) ## Default S3 method: as.tis(x, ...) is.tis(x)
data |
a numeric vector or matrix of the observed time-series values. |
start |
the time of the first observation. This can be a |
... |
other args to be passed to the method called by the generic
function. |
tif |
a ti Frequency, given as either a numerical code or a string.
|
frequency |
As an alternative to supplying a |
end |
the time of the last observation, specified in the same way as |
x |
object to be tested ( |
The function tis
is used to create tis
objects, which
are vectors or matrices with class of "tis"
and a start
attribute that is a ti
(time index) object. Time-indexed
series are a form of time series that is more flexible
than the standard ts
time series. While observations for a
ts
object are supposed to have been sampled at equispaced
points in time, the observation times for a tis
object are the
times given by successive increments of the more flexible time index
contained in the series start
attribute. There is a close
correspondence between Fame time series and tis
objects, in
that all of the Fame frequencies have corresponding tif
codes.
tis
objects operate much like vanilla R ts
objects.
Most of the methods implemented for ts
objects have tis
variants as well. Evaluate methods(class = "tis")
to see a
list of them.
One way or another, tis
needs to figure out how to create a
start
attribute. If start
is supplied, the function
ti
is called with it, tif
and frequency
as
arguments. The same process is repeated for end
if it was
supplied. If only one of start
and end
was supplied, the
other is inferred from it and the number of observations in data
. If
both start
and end
are supplied, the function rep
is used to make data
the length implied by end - start + 1
.
as.tis
is a generic function with specialized methods for other
kinds of time series, including zoo
series from zoo.
The fallback default method calls tis(x, ...)
.
tis
and as.tis
return time-indexed series.
is.tis
returns TRUE or FALSE.
If the index
of a zoo
series is a ti
,
the coercion as.tis.zoo
does is trivial. For other kinds of
zoo
series, the function inferTi
tries to figure out a time
index that matches the times of the index
of the zoo series.
This may fail, as there are infinitely more possible kinds of zoo
indexes than the finite number of time index frequencies.
Compare with ts
. See ti
for
details on time indexes. cbind.tis
combines several
time indexed series into a multivariate tis
, while
mergeSeries
merges series, and convert
and
aggregate
convert series from one frequency to another.
start.tis
and end.tis
return ti
objects, while ti.tis
returns a vector ti
. There
is a print method print.tis
and several plotting
methods, including lines.tis
and points.tis
.
The window.tis
method is also sufficiently different
from the ts
one to deserve its own documentation.
tis(1:48, start = c(2000, 1), freq = 12) tis(1:48, start = ti(20000101, tif = "monthly")) ## same result tis(0, start = c(2000,1), end = c(2000,52), tif = "weekly")
tis(1:48, start = c(2000, 1), freq = 12) tis(1:48, start = ti(20000101, tif = "monthly")) ## same result tis(0, start = c(2000,1), end = c(2000,52), tif = "weekly")
Applies linear filtering to a univariate tis
series or to each
column separately of a multivariate tis
series.
tisFilter(x, ...)
tisFilter(x, ...)
x |
a univariate or multivariate time series. |
... |
arguments passed along to |
A tis
time indexed series with leading and trailing
NA
values stripped.
If ever the filter()
function is made generic, as it should be,
this function could become the tis
method for it.
x <- tis(1:100, start = c(2000,1), freq = 12) tisFilter(x, rep(1, 3)) tisFilter(x, rep(1, 3), sides = 1) tisFilter(x, rep(1, 3), sides = 1, circular = TRUE)
x <- tis(1:100, start = c(2000,1), freq = 12) tisFilter(x, rep(1, 3)) tisFilter(x, rep(1, 3), sides = 1) tisFilter(x, rep(1, 3), sides = 1, circular = TRUE)
Reads tis
(Time Indexed Series) from a csv file,
returning the series in a list, and optionally storing them in an environment.
tisFromCsv(csvFile, dateCol = "date", dateFormat = "%Y%m%d", tz = "", tif = NULL, defaultTif = "business", save = F, envir = parent.frame(), naNumber = NULL, chopNAs = TRUE, tolerance = sqrt(.Machine$double.eps), ...)
tisFromCsv(csvFile, dateCol = "date", dateFormat = "%Y%m%d", tz = "", tif = NULL, defaultTif = "business", save = F, envir = parent.frame(), naNumber = NULL, chopNAs = TRUE, tolerance = sqrt(.Machine$double.eps), ...)
csvFile |
A file name, connection, or URL acceptable to
|
dateCol |
name of the column holding dates. This column must be present in the file. |
dateFormat |
format of the dates in |
tz |
the time zone to be used by |
tif |
time index frequency of the data. If this is |
defaultTif |
If the frequency can't be inferred from the dates in
the |
save |
If true, save the individual series in the enviroment
given by the |
envir |
if |
naNumber |
if non- |
chopNAs |
if |
tolerance |
Used to determine whether or not numbers in the file
are close enough to |
... |
Additional arguments passed along to the underlying
|
File Requirements: The csv file must have column names
across the top, and everything but the first row should be numeric.
There must be as many column names (enclosed in quotes) as there are
columns, and the column named by dateCol
must have dates in the
format indicated by dateFormat
. The dateCol
column must be present.
Missing (NA) values: Missing and NA values are the same thing.
The underlying read.csv
has "," as its default separator and
"NA" as its default na.string, so the rows
20051231,,13,,42,NA, 20060131,NA,14,,43,,NA
indicate NA
values for both the Dec 2005 and Jan 2006
observations of the first, third, fifth and sixth series.
The values in the file are read into a single large tis
series,
with a tif
(Time Index Frequency) inferred from the first six
dates in the ymd column. The first date is converted to a ti
(Time Index) of that frequency and becomes the start
of the
series. If chopNAs
is TRUE
, each individual column is
then windowed via naWindow
to strip off leading and trailing
NA
values, and the resulting series are put into a list with
names given by lower-casing the column names from the csv file. If
save
is TRUE
, the series are also stored in envir
using those same names.
A list of tis
time series, one per column of the csv file.
The list is returned invisibly if save
is TRUE
.
ti
, tis
, read.csv
,
read.table
The plotting functions tisPlot
and
scatterPlot
leave an object named latestPlot
in the
frame from which they were called. tisLegend
uses that object
to set legend arguments (which you can override) and sets reasonable
defaults for other arguments.
tisLegend(..., xrel = 0.1, yrel = 0.1, xjust = 0, yjust = 1, boxType ="n", ncol = 1, cex = 1)
tisLegend(..., xrel = 0.1, yrel = 0.1, xjust = 0, yjust = 1, boxType ="n", ncol = 1, cex = 1)
... |
optional arguments to be passed on to |
xrel , yrel
|
Optional numbers between 0 and 1 to specify placement relative to the boundaries of the plot. |
xjust , yjust , ncol
|
passed along to |
boxType |
passed along as |
cex |
gets multiplied by the |
This function is not strictly necessary, in that you could just
call legend
directly. tisLegend
makes things a
bit easier, however, by using the same argument names as
tisPlot
and scatterPlot
to specify color
,
lineType
, plotChar
and boxType
, rather than the
less intuitive col
, lty
, pch
and bty
names. The xrel
and yrel
arguments provide an
alternative way to specify legend placement, one that is used by the
ChartMaker program.
a list of the arguments that were sent on to legend
, with
class "tisLegend"
tisPlot
is a function with dozens of options for creating
high quality time series plots. Can be used with screenPage
.
tisPlot(..., leftAxis = TRUE, plotType = "l", lineType = "solid", lineWidth = 1.5, plotChar = "*", dataCex = 1, color = 1, midPoints = TRUE, dropNA = FALSE, xOffset = 0, xAxisMin = NULL, xAxisMax = NULL, xExpandBy = 0.04, xTickFreq = "Auto", xTickSkip = 0, xUnlabeledTickFreq = "None", xUnlabeledTickSkip = 0, xMinorTickFreq = "None", xMinorTickSkip = 0, dateFormat = "Auto", xCex = 1, midLabels = FALSE, yearLabels = FALSE, xAxisLabel = NULL, xSpace = 4, log = FALSE, leftAxisMin = NULL, leftAxisMax = NULL, leftExpandBy = 0.04, leftTicks = 5, leftTickLocations = NULL, labelLeftTicks = FALSE, leftTickLabels = NULL, rightAxisMin = NULL, rightAxisMax = NULL, rightExpandBy = 0.04, rightTicks = 5, rightTickLocations = NULL, labelRightTicks = TRUE, rightTickLabels = NULL, yCex = 1, extendTopTick = TRUE, cex = 1, head = NULL, headAlign = 0.5, headCex = 1.5, sub = NULL, subCex = 0.85, leftTopLabel = NULL, rightTopLabel = NULL, topLabelAlign = 0, labCex = 1, leftInsideLabel = NULL, rightInsideLabel = NULL, innerLine = 0.5, innerOffset = 0.05, innerCex = 0.8, foot = NULL, footColor = "black", footAlign = 0, footCex = 0.8, footSpace = -1, tck = 0.03, axisWidth = 2, start = 0, end = 0, boxType = "u", leftMargin = -1, rightMargin = -1, topMargin = -1, bottomMargin = -1, nberShade = FALSE, shadeDates = NULL, shadeColor = "gray", shadeBorder = FALSE, polyArgs = list())
tisPlot(..., leftAxis = TRUE, plotType = "l", lineType = "solid", lineWidth = 1.5, plotChar = "*", dataCex = 1, color = 1, midPoints = TRUE, dropNA = FALSE, xOffset = 0, xAxisMin = NULL, xAxisMax = NULL, xExpandBy = 0.04, xTickFreq = "Auto", xTickSkip = 0, xUnlabeledTickFreq = "None", xUnlabeledTickSkip = 0, xMinorTickFreq = "None", xMinorTickSkip = 0, dateFormat = "Auto", xCex = 1, midLabels = FALSE, yearLabels = FALSE, xAxisLabel = NULL, xSpace = 4, log = FALSE, leftAxisMin = NULL, leftAxisMax = NULL, leftExpandBy = 0.04, leftTicks = 5, leftTickLocations = NULL, labelLeftTicks = FALSE, leftTickLabels = NULL, rightAxisMin = NULL, rightAxisMax = NULL, rightExpandBy = 0.04, rightTicks = 5, rightTickLocations = NULL, labelRightTicks = TRUE, rightTickLabels = NULL, yCex = 1, extendTopTick = TRUE, cex = 1, head = NULL, headAlign = 0.5, headCex = 1.5, sub = NULL, subCex = 0.85, leftTopLabel = NULL, rightTopLabel = NULL, topLabelAlign = 0, labCex = 1, leftInsideLabel = NULL, rightInsideLabel = NULL, innerLine = 0.5, innerOffset = 0.05, innerCex = 0.8, foot = NULL, footColor = "black", footAlign = 0, footCex = 0.8, footSpace = -1, tck = 0.03, axisWidth = 2, start = 0, end = 0, boxType = "u", leftMargin = -1, rightMargin = -1, topMargin = -1, bottomMargin = -1, nberShade = FALSE, shadeDates = NULL, shadeColor = "gray", shadeBorder = FALSE, polyArgs = list())
... |
any number of univariate or multivariate |
leftAxis |
logical. |
plotType |
type of plot desired. Values are |
lineType |
character or numeric vector specifying the line type for each
series. The default is |
lineWidth |
numeric vector of line widths for the series. The default value is
|
plotChar |
vector of characters (or numbers for plotting symbols – see the
help for |
dataCex |
numeric vector. |
color |
character or numeric vector specifies color for each series. Default is 1, the device default foreground color. |
midPoints |
logical. |
dropNA |
if |
xOffset |
Shifts the data points for series[i] to the right by
|
xAxisMin |
minimum value of the x axis. If non-NULL, this overrides the
calculation described in |
xAxisMax |
maximum value of the x axis. If non-NULL, this overrides the
calculation described in |
xExpandBy |
a single number or two numbers between 0 and 1. |
xTickFreq |
a string like the ones returned by Two special strings can also be given. "none" means no labelled
tick marks, while "auto" tries (not always successfully) to come up
with reasonable tick locations automatically. "auto" also overrides
any The default is "auto". |
xTickSkip |
a number used with |
xUnlabeledTickFreq |
same as |
xUnlabeledTickSkip |
same as |
xMinorTickFreq |
same as |
xMinorTickSkip |
same as |
dateFormat |
format string for x axis date labels. See |
xCex |
|
midLabels |
if |
yearLabels |
if |
xAxisLabel |
text to appear centered under the x axis. Must be a single
character string, multi-line |
xSpace |
lines of space to set aside directly beneath the x-axis to hold
tick, year and/or axis labels. Default is |
log |
if |
leftAxisMin |
minimum value of the left axis. If non-NULL, this overrides the
calculation described in |
leftAxisMax |
maximum value of the left axis. If non-NULL, this overrides the
calculation described in |
leftExpandBy |
a single number or two numbers between 0 and 1. |
leftTicks |
number of ticks to draw on left axis at "pretty" locations. Default
is 5. This argument is ignored if |
leftTickLocations |
if non-NULL, a vector of desired tick locations or a string that
evaluates to such a vector. The default value NULL lets the setting
for |
labelLeftTicks |
If |
leftTickLabels |
character vector of tick labels or NULL (the default). If NULL and
|
rightAxisMin |
minimum value of the right axis. If non-NULL, this overrides the
calculation described in |
rightAxisMax |
maximum value of the right axis. If non-NULL, this overrides the
calculation described in |
rightExpandBy |
a single number or two numbers between 0 and 1. |
rightTicks |
number of ticks to draw on right axis at "pretty" locations. Default
is 5. This argument is ignored if |
rightTickLocations |
if non-NULL, a vector of desired tick locations or a string that
evaluates to such a vector. The default value NULL lets the setting
for |
labelRightTicks |
If |
rightTickLabels |
character vector of tick labels or NULL (the default). If NULL and
|
yCex |
|
extendTopTick |
if |
cex |
the base character expansion factor by which all of the
|
head |
text to appear at the top of the figure region, with alignment
determined by |
headAlign |
number indicating justification for the strings in |
headCex |
|
sub |
text to appear just under |
subCex |
|
leftTopLabel |
text to appear at the top of the left axis, with alignment
determined by |
rightTopLabel |
text to appear at the top of the right axis, with alignment
determined by |
topLabelAlign |
number indicating alignment for the strings in |
labCex |
|
leftInsideLabel |
text to appear left justified and just inside the upper left corner of the plot region. No default. |
rightInsideLabel |
text to appear right justified and just inside the upper right corner of the plot region. No default. |
innerOffset |
number between 0 and 1, a fractional offset for the inside labels.
The left edge of |
innerLine |
Number of lines in from the top edge of the plot to put the first line of the inside labels. |
innerCex |
|
foot |
text to appear at the bottom of the figure region, with alignment
determined by |
footAlign |
number indicating justification for the strings in |
footCex |
|
footColor |
character or numeric vector as long as |
footSpace |
lines of space to set aside directly beneath the space allocated by
|
tck |
The length of |
axisWidth |
line width for the axes and box (if any). Default is 2. |
start |
starting date for the plot. The default is the earliest start time
of all the series. This argument can be supplied in any of the forms
understood by |
end |
end date for the plot. The default is the latest end time
of all the series. This argument can be supplied in any of the forms
understood by |
boxType |
character representing the type of box. Characters |
leftMargin |
lines of space for the left margin. Default value (-1) figures this out automatically. |
rightMargin |
lines of space for the right margin. Default value (-1) figures this out automatically. |
topMargin |
lines of space for the top margin. Default value (-1) figures this out automatically. |
bottomMargin |
lines of space for the bottom margin. Default value (-1) figures this out automatically. |
nberShade |
if |
shadeDates |
a matrix of yyyymmdd dates with two columns named 'Start'
and 'End' that specifies the date ranges to be shaded.
|
shadeColor |
color to shade periods specified by |
shadeBorder |
if shading is being done, this argument tells what color the border
of the shaded areas should be drawn in. It can also be a logical,
in which case |
polyArgs |
additional args that are passed along to the |
leftAxis
, plotType
, lineType
, lineWidth
,
plotChar
, dataCex
, color
and midPoints
are
all cyclically repeated to make them length nSeries
, the number
of series plotted.
Each of the text items head
, sub
, leftTopLabel
,
rightTopLabel
, leftInsideLabel
, rightInsideLabel
,
foot
, and xAxisLabel
can be given as a string, a
collections of strings, or as a string that gets evaluated to one of
the first two. (But xAxisLabel
takes only a single string.)
See the help details for evalOrEcho
to see how this works.
tisPlot
invisibly returns a list of class "tisPlot" and
elements named series
, dateFormat
, plotType
,
lineType
, dataCex
, color
, plotChar
,
lineWidth
, yLegendOffset
, cex
, xRange
,
leftRange
, rightRange
, midPoints
and par
.
This list is useful mostly as an argument to tisLegend
.
The arguments for tisPlot
and its sister function
scatterPlot
have more descriptive names than the corresponding
arguments in plot
. They are also all of unique types, unlike,
for example, the lty
argument in the usual R plotting
functions, which can be either character or numeric. Limiting each
argument to a single type was done to make it easier to design a user
interface to drive the functions.
Use tisLegend
to add legends to a plot created by
tisPlot
or scatterPlot
.
evalOrEcho
, scatterPlot
,
tisLegend
, nberShade
firstTis <- tis(cumsum(rnorm(120)), start = c(1996,1), freq = 12) secondTis <- tis(cumsum(rnorm(120)), start = c(1996,1), freq = 12) tisPlot(firstTis, secondTis, color = c("red", "green"), lineType = "solid", head = "Two Random Walks") tisLegend(legend = c("Random Walk 1", "Random Walk 2")) series <- tis(cumsum(rnorm(200)), start = c(1960,1), tif = "quarterly") tisPlot(series, xMinorTickFreq = "annual", nberShade = TRUE, head = "A Random Walk", sub = "Looks like an econ series", rightTopLabel = "$Billions") romerLines()
firstTis <- tis(cumsum(rnorm(120)), start = c(1996,1), freq = 12) secondTis <- tis(cumsum(rnorm(120)), start = c(1996,1), freq = 12) tisPlot(firstTis, secondTis, color = c("red", "green"), lineType = "solid", head = "Two Random Walks") tisLegend(legend = c("Random Walk 1", "Random Walk 2")) series <- tis(cumsum(rnorm(200)), start = c(1960,1), tif = "quarterly") tisPlot(series, xMinorTickFreq = "annual", nberShade = TRUE, head = "A Random Walk", sub = "Looks like an econ series", rightTopLabel = "$Billions") romerLines()
Returns a ti
for the current date.
today(tif = "daily")
today(tif = "daily")
tif |
a ti Frequency, given as either a numerical code or a string.
|
A ti
object of the specified ti frequency that contains the
current date in the time interval it represents. For example, if
tif
is "monthly"
, the returned ti
object will
be for the current month.
updateList
compares the names of oldlist
and
newlist
, deletes the matching elements from a copy of
oldlist
, then returns the result of concatenating that list
with newlist
.
updateColumns
updates columns of first series from same-named
columns of second series using mergeSeries()
. If second series
has columns with names not found in colnames of first series, those
columns are cbind()
'ed onto first series.
updateColumns(oldmat, newmat) updateList(oldlist, newlist)
updateColumns(oldmat, newmat) updateList(oldlist, newlist)
oldmat |
a multivariate |
newmat |
a multivariate |
oldlist |
a list |
newlist |
a list |
updateList
returns the updated list.
updateColumns
returns a multivariate tis
series
window.tis
extracts the subset of the object x
observed
between the times start
and end
.
## S3 method for class 'tis' window(x, start = NULL, end = NULL, extend = FALSE, noWarn = FALSE, ...)
## S3 method for class 'tis' window(x, start = NULL, end = NULL, extend = FALSE, noWarn = FALSE, ...)
x |
a |
start |
the start time of the period of interest. |
end |
the end time of the period of interest. |
extend |
logical. If |
noWarn |
logical. If |
... |
other arguments to this function are ignored. |
The start and end times can be ti
objects, or anything that
ti(z, tif = tif, freq = frequency)
, can turn into a ti
object.
A tis
object that starts and ends at the given times.
The replacement method window<-.tis
has not been implemented.
Use the subscript operator with a ti
argument to replace values
of a tis
object.
z <- tis(1:24, start = c(2001,1), freq = 12) z2 <- window(z, start = 19991231, extend = TRUE) ## z2 extends back with NA's window(z, end = end(z) - 3)
z <- tis(1:24, start = c(2001,1), freq = 12) z2 <- window(z, start = 19991231, extend = TRUE) ## z2 extends back with NA's window(z, end = end(z) - 3)
Extract the year, month or day, or all three (in yyyymmdd
form), or the quarter, from a jul, ti, or from any object that
jul()
can handle.
ymd(x, ...) ## S3 method for class 'jul' ymd(x, ...) ## S3 method for class 'ssDate' ymd(x, ...) ## S3 method for class 'ti' ymd(x, offset = 1, ...) ## Default S3 method: ymd(x, ...) year(x, ...) quarter(x, ...) month(x, ...) day(x, ...)
ymd(x, ...) ## S3 method for class 'jul' ymd(x, ...) ## S3 method for class 'ssDate' ymd(x, ...) ## S3 method for class 'ti' ymd(x, offset = 1, ...) ## Default S3 method: ymd(x, ...) year(x, ...) quarter(x, ...) month(x, ...) day(x, ...)
x |
a |
... |
other args to be passed to the method called by the generic
function. |
offset |
for |
year
, quarter
, month
and day
call
ymd
, and thus understand the same arguments as it does. The
default implementation ymd.default
passes it's arguments to a
call to the function jul
, so all of these functions work the
same way that function does.
ymd
and it's variants return numeric objects in yyyymmdd form.
year
, quarter
, month
and day
return
numeric objects.
ymd()
with no arguments returns today's yyyymmdd.
ymd() ## today's date and time weekFromNow <- ymd(today() + 7) ## today() returns a daily ti year(jul(today())) month(Sys.time()) ## create a monthly tis (Time Indexed Series) aTis <- tis(0, start = c(2000, 1), end = c(2004, 12), freq = 12) ymd(ti(aTis)) ## the yyyymmdd dates of the observations
ymd() ## today's date and time weekFromNow <- ymd(today() + 7) ## today() returns a daily ti year(jul(today())) month(Sys.time()) ## create a monthly tis (Time Indexed Series) aTis <- tis(0, start = c(2000, 1), end = c(2004, 12), freq = 12) ymd(ti(aTis)) ## the yyyymmdd dates of the observations
ymdXy
returns a list of x and y coordinates that can be fed
to polygon
to draw NBER shadings on the current plot.
If the last row of the ymds
argument has a Start entry but an "NA"
End entry and openShade
is FALSE
, the returned list will
not have coordinates for the last row, but will instead include a
vLine element that gives the x coordinate of the last Start. If
openShade
is TRUE
(the default), the list includes x
and y coordinates for the last row of ymds
, using the second
element of the horizontal range determined by the xrange
parameter as its end time.
ymdShade
shades date ranges on the current tisPlot.
on the current plot. It calls ymdXy
to get x and y
coordinates for the areas to be shaded and then passes those
coordinates along with its own arguments to polygon
to
do the shading. It also draws a vertical line at the appropriate
location if the list returned by ymdXy
has a vLine element.
ymdShade(ymds, col = grey(0.8), border = FALSE, xpd = FALSE, xrange = NULL, openShade = TRUE, ...) ymdXy(ymds, xrange = NULL, openShade = TRUE)
ymdShade(ymds, col = grey(0.8), border = FALSE, xpd = FALSE, xrange = NULL, openShade = TRUE, ...) ymdXy(ymds, xrange = NULL, openShade = TRUE)
All but ymds
are passed along to polygon
:
ymds |
a matrix of yyyymmdd dates with two columns named 'Start'
and 'End' that specifies the date ranges to be shaded.
|
col |
color to shade recessionary periods |
border |
the default ( |
xpd |
should clipping take place? |
... |
other args passed to |
xrange |
horizontal range over which recession shading should be
drawn. The default value |
openShade |
governs how |
As described above, ymdXy
returns a list. ymdShade
does not return anything useful.
require("datasets") plot(presidents, type='n', ylab="Presidents approval rating") ymdShade(nberDates()) lines(presidents)
require("datasets") plot(presidents, type='n', ylab="Presidents approval rating") ymdShade(nberDates()) lines(presidents)