zoo/0000755000175100001440000000000014415770741011111 5ustar hornikuserszoo/NAMESPACE0000644000175100001440000002565714415347256012350 0ustar hornikusers## name spaces needed for S3 methods import("stats", "utils", "graphics", "lattice", "grDevices") ## C code useDynLib("zoo") export( ## zoo core functionality "zoo", "zooreg", "as.zoo", "as.zoo.default", "as.zooreg", "as.zooreg.default", "ifelse.zoo", "is.zoo", "merge.zoo", "read.zoo", "read.table.zoo", "read.csv.zoo", "read.csv2.zoo", "read.delim.zoo", "read.delim2.zoo", "write.zoo", "cbind.zoo", "rbind.zoo", "median.zoo", "quantile.zoo", "rev.zoo", "xtfrm.zoo", ## plotting "plot.zoo", "make.par.list", "xblocks", "xblocks.default", ## *** temporary -- these are Deprecated "panel.plot.default", "panel.plot.custom", ## new time series functionality "coredata", "coredata.default", "coredata<-", "frequency<-", "index", "index2char", "index<-", "is.regular", "time<-", ## rolling operations "rollapply", "rollapplyr", "rollmax", "rollmaxr", "rollmax.default", "rollmean", "rollmeanr", "rollmean.default", "rollmedian", "rollmedianr", "rollmedian.default", "rollsum", "rollsumr", "rollsum.default", ## NA operations "na.approx", "na.approx.default", "na.fill", "na.fill.default", "na.fill0", "na.locf", "na.locf.default", "na.locf0", "na.spline", "na.spline.default", "na.StructTS", "na.trim", "na.trim.default", "na.trim.ts", "na.aggregate", "na.aggregate.default", ## new index classes "yearmon", "as.yearmon", "as.yearmon.default", "Sys.yearmon", "yearqtr", "as.yearqtr", "as.yearqtr.default", "format.yearqtr", "Sys.yearqtr", # *** temporary -- these are Deprecated "panel.lines.ts", "panel.lines.its", "panel.lines.tis", "panel.lines.zoo", "panel.points.ts", "panel.points.its", "panel.points.tis", "panel.points.zoo", "panel.text.ts", "panel.text.its", "panel.text.tis", "panel.text.zoo", # *** are these actually used by anyone? "panel.segments.ts", "panel.segments.its", "panel.segments.tis", "panel.segments.zoo", "panel.rect.ts", "panel.rect.its", "panel.rect.tis", "panel.rect.zoo", "panel.polygon.ts", "panel.polygon.its", "panel.polygon.tis", "panel.polygon.zoo", ## auxiliary generics/methods "MATCH", "MATCH.default", "MATCH.times", "ORDER", "ORDER.default", ## other "as.Date", "as.Date.numeric", "as.Date.yearmon", "as.Date.yearqtr", "as.Date.ts", ## ggplot2 interface (currently fully exported) "facet_free", "fortify.zoo", "autoplot.zoo", "yearmon_trans", "scale_x_yearmon", "scale_y_yearmon", "scale_type.yearqtr", "yearqtr_trans", "scale_x_yearqtr", "scale_y_yearqtr", "scale_type.yearmon" ) ## methods for class zoo S3method("Ops", "zoo") S3method("[", "zoo") S3method("[<-", "zoo") S3method("$", "zoo") S3method("$<-", "zoo") S3method(".DollarNames", "zoo") S3method("aggregate", "zoo") S3method("as.data.frame", "zoo") S3method("as.list", "zoo") S3method("as.matrix", "zoo") S3method("as.ts", "zoo") S3method("as.vector", "zoo") S3method("barplot", "zoo") S3method("boxplot", "zoo") S3method("c", "zoo") S3method("cbind", "zoo") S3method("coredata", "zoo") S3method("coredata<-", "zoo") S3method("cummax", "zoo") S3method("cummin", "zoo") S3method("cumprod", "zoo") S3method("cumsum", "zoo") S3method("cycle", "zoo") S3method("deltat", "zoo") S3method("diff", "zoo") S3method("dim<-", "zoo") S3method("end", "zoo") S3method("frequency", "zoo") S3method("frequency<-", "zoo") S3method("head", "zoo") S3method("ifelse", "zoo") S3method("index", "zoo") S3method("index<-", "zoo") S3method("is.regular", "zoo") S3method("lag", "zoo") S3method("lines", "zoo") S3method("llines", "zoo") S3method("lpoints", "zoo") S3method("ltext", "zoo") S3method("mean", "zoo") S3method("median", "zoo") S3method("merge", "zoo") S3method("na.approx", "zoo") S3method("na.contiguous", "zoo") S3method("na.fill", "zoo") S3method("na.spline", "zoo") S3method("na.StructTS", "zoo") S3method("names", "zoo") S3method("names<-", "zoo") S3method("plot", "zoo") S3method("points", "zoo") S3method("print", "zoo") S3method("quantile", "zoo") S3method("range", "zoo") S3method("rbind", "zoo") S3method("rev", "zoo") S3method("rollapply", "zoo") S3method("rollmax", "zoo") S3method("rollmean", "zoo") S3method("rollmedian", "zoo") S3method("rollsum", "zoo") S3method("scale", "zoo") S3method("split", "zoo") S3method("subset", "zoo") S3method("start", "zoo") S3method("str", "zoo") S3method("summary", "zoo") S3method("t", "zoo") S3method("tail", "zoo") S3method("time", "zoo") S3method("time<-", "zoo") S3method("transform", "zoo") S3method("window", "zoo") S3method("window<-", "zoo") S3method("with", "zoo") S3method("xblocks", "zoo") S3method("xtfrm", "zoo") S3method("xyplot", "zoo") ## conditional registration of ggplot2 methods if(getRversion() >= "3.6.0") { S3method(ggplot2::autoplot, "zoo") S3method(ggplot2::fortify, "zoo") S3method(ggplot2::scale_type, "yearmon") S3method(ggplot2::scale_type, "yearqtr") } ## methods for class zooreg S3method("as.ts", "zooreg") S3method("deltat", "zooreg") S3method("frequency", "zooreg") S3method("frequency<-", "zooreg") S3method("index<-", "zooreg") S3method("is.regular", "zooreg") S3method("lag", "zooreg") S3method("na.approx", "zooreg") S3method("na.spline", "zooreg") S3method("rev", "zooreg") S3method("time<-", "zooreg") ## methods for class ts S3method("as.Date", "ts") S3method("coredata", "ts") S3method("coredata<-", "ts") S3method("index", "ts") S3method("is.regular", "ts") S3method("na.approx", "ts") S3method("na.fill", "ts") S3method("na.spline", "ts") S3method("na.StructTS", "ts") S3method("na.trim", "ts") S3method("rollapply", "ts") S3method("rollmax", "ts") S3method("rollmean", "ts") S3method("rollmedian", "ts") S3method("rollsum", "ts") S3method("xblocks", "ts") ## methods for class irts S3method("coredata", "irts") S3method("coredata<-", "irts") ## methods for class its S3method("coredata", "its") S3method("coredata<-", "its") S3method("llines", "its") S3method("lpoints", "its") S3method("ltext", "its") S3method("xyplot", "its") ## methods for class tis S3method("llines", "tis") S3method("lpoints", "tis") S3method("ltext", "tis") S3method("xyplot", "tis") ## methods for class yearmon S3method("-", "yearmon") S3method("as.Date", "yearmon") S3method("Axis", "yearmon") S3method("MATCH", "yearmon") S3method("Ops", "yearmon") S3method("Summary", "yearmon") S3method("[", "yearmon") S3method("[[", "yearmon") S3method("as.POSIXct", "yearmon") S3method("as.POSIXlt", "yearmon") S3method("as.character", "yearmon") S3method("as.list", "yearmon") S3method("as.numeric", "yearmon") S3method("as.data.frame", "yearmon") S3method("c", "yearmon") S3method("cycle", "yearmon") S3method("diff", "yearmon") S3method("format", "yearmon") S3method("is.numeric", "yearmon") S3method("mean", "yearmon") S3method("months", "yearmon") S3method("quarters", "yearmon") S3method("print", "yearmon") S3method("range", "yearmon") S3method("summary", "yearmon") S3method("unique", "yearmon") S3method("xtfrm", "yearmon") ## methods for class yearqtr S3method("-", "yearqtr") S3method("as.Date", "yearqtr") S3method("Axis", "yearqtr") S3method("MATCH", "yearqtr") S3method("Ops", "yearqtr") S3method("Summary", "yearqtr") S3method("[", "yearqtr") S3method("[[", "yearqtr") S3method("as.POSIXct", "yearqtr") S3method("as.POSIXlt", "yearqtr") S3method("as.character", "yearqtr") S3method("as.list", "yearqtr") S3method("as.numeric", "yearqtr") S3method("as.data.frame", "yearqtr") S3method("c", "yearqtr") S3method("cycle", "yearqtr") S3method("diff", "yearqtr") S3method("format", "yearqtr") S3method("is.numeric", "yearqtr") S3method("mean", "yearqtr") S3method("months", "yearqtr") S3method("quarters", "yearqtr") S3method("print", "yearqtr") S3method("range", "yearqtr") S3method("summary", "yearqtr") S3method("unique", "yearqtr") S3method("xtfrm", "yearqtr") ## methods for class timeDate/timeSeries S3method("MATCH", "timeDate") S3method("ORDER", "timeDate") S3method("as.zoo", "timeSeries") ## default methods and methods for misc classes S3method("MATCH", "default") S3method("MATCH", "Date") S3method("MATCH", "POSIXct") S3method("MATCH", "POSIXlt") S3method("MATCH", "times") S3method("ORDER", "default") S3method("ORDER", "chron") S3method("ORDER", "dates") S3method("ORDER", "times") S3method("as.yearmon", "default") S3method("as.yearqtr", "default") S3method("coredata", "default") S3method("index", "default") S3method("index2char", "default") S3method("index2char", "numeric") S3method("index2char", "POSIXt") S3method("is.regular", "default") S3method("na.approx", "default") S3method("na.fill", "default") S3method("na.locf", "default") S3method("na.locf", "data.frame") S3method("na.spline", "default") S3method("na.trim", "default") S3method("na.aggregate", "default") S3method("na.contiguous", "data.frame") S3method("na.contiguous", "list") S3method("rollapply", "default") S3method("rollmax", "default") S3method("rollmean", "default") S3method("rollmedian", "default") S3method("rollsum", "default") S3method("xblocks", "default") ## coercion to classes Date, list, yearmon, yearqtr, zoo, zooreg S3method("as.Date", "default", ".as_Date_default") S3method("as.Date", "mondate", ".as_Date_default") S3method("as.Date", "numeric") S3method("as.list", "ts") S3method("as.yearmon", "date") S3method("as.yearmon", "Date") S3method("as.yearmon", "timeDate") S3method("as.yearmon", "jul") S3method("as.yearmon", "mondate") S3method("as.yearmon", "POSIXt") S3method("as.yearmon", "character") S3method("as.yearmon", "dates") S3method("as.yearmon", "integer") S3method("as.yearmon", "numeric") S3method("as.yearmon", "factor") S3method("as.yearmon", "ti") S3method("as.yearmon", "yearqtr") S3method("as.yearqtr", "date") S3method("as.yearqtr", "Date") S3method("as.yearqtr", "timeDate") S3method("as.yearqtr", "jul") S3method("as.yearqtr", "mondate") S3method("as.yearqtr", "POSIXt") S3method("as.yearqtr", "character") S3method("as.yearqtr", "dates") S3method("as.yearqtr", "integer") S3method("as.yearqtr", "numeric") S3method("as.yearqtr", "factor") S3method("as.yearqtr", "yearqtr") S3method("as.yearqtr", "ti") S3method("as.zoo", "default") S3method("as.zoo", "data.frame") S3method("as.zoo", "factor") S3method("as.zoo", "fts") S3method("as.zoo", "irts") S3method("as.zoo", "its") S3method("as.zoo", "matrix") S3method("as.zoo", "mcmc") S3method("as.zoo", "tis") S3method("as.zoo", "ts") S3method("as.zoo", "xts") S3method("as.zoo", "zoo") S3method("as.zoo", "zooreg") S3method("as.zooreg", "default") S3method("as.zooreg", "tis") S3method("as.zooreg", "ts") S3method("as.zooreg", "xts") S3method("as.zooreg", "zoo") zoo/demo/0000755000175100001440000000000012213624641012024 5ustar hornikuserszoo/demo/zoo-overplot.R0000644000175100001440000001343113323072605014630 0ustar hornikusers # From: # http://www.nabble.com/Re%3A-mark-areas-on-time-series-plot-p23112841.html Lines <- '"Time","IEMP (rand/US$) Index","Distress" 01/08/81,-0.02,0 01/09/81,0.08,0 01/10/81,-0.09,0 01/11/81,0.05,0 01/12/81,0.11,0 01/01/82,0.05,0 01/02/82,-0.04,0 01/03/82,0.07,0 01/04/82,0.07,0 01/05/82,0,0 01/06/82,0.06,0 01/07/82,-0.02,0 01/08/82,0.07,0 01/09/82,-0.11,0 01/10/82,0.04,0 01/11/82,-0.36,0 01/12/82,-0.01,0 01/01/83,-0.21,0 01/02/83,-0.16,1 01/03/83,0.19,1 01/04/83,-0.06,1 01/05/83,0.06,1 01/06/83,0.13,1 01/07/83,-0.01,1 01/08/83,0,1 01/09/83,-0.01,1 01/10/83,0.06,1 01/11/83,0.09,1 01/12/83,0.04,1 01/01/84,0.02,1 01/02/84,-0.01,1 01/03/84,0.03,1 01/04/84,0.03,1 01/05/84,0,1 01/06/84,0.03,1 01/07/84,0.13,1 01/08/84,0.18,1 01/09/84,0.07,1 01/10/84,0.12,1 01/11/84,-0.16,1 01/12/84,0.13,1 01/01/85,-0.06,1 01/02/85,-0.07,1 01/03/85,0.04,1 01/04/85,-0.12,1 01/05/85,-0.01,1 01/06/85,-0.17,1 01/07/85,0.09,1 01/08/85,0.08,1 01/09/85,0.08,1 01/10/85,-0.07,1 01/11/85,-0.01,1 01/12/85,-0.01,1 01/01/86,-0.26,1 01/02/86,-0.11,1 01/03/86,0.02,1 01/04/86,0.01,1 01/05/86,0.04,1 01/06/86,0.12,1 01/07/86,-0.05,0 01/08/86,-0.08,0 01/09/86,-0.17,0 01/10/86,-0.06,0 01/11/86,0,0 01/12/86,0.02,0 01/01/87,-0.16,0 01/02/87,-0.05,0 01/03/87,-0.04,0 01/04/87,0.01,0 01/05/87,0.03,0 01/06/87,0.01,0 01/07/87,0,0 01/08/87,0.02,0 01/09/87,0,0 01/10/87,-0.02,0 01/11/87,0.02,0 01/12/87,0.01,0 01/01/88,0.02,0 01/02/88,0.09,0 01/03/88,0.09,0 01/04/88,0.04,0 01/05/88,0.09,0 01/06/88,-0.05,0 01/07/88,0.11,0 01/08/88,0.08,0 01/09/88,-0.04,0 01/10/88,0.08,0 01/11/88,0.01,0 01/12/88,-0.02,0 01/01/89,0,0 01/02/89,0.07,0 01/03/89,0.06,0 01/04/89,0.03,0 01/05/89,0.09,0 01/06/89,0.02,0 01/07/89,-0.04,0 01/08/89,-0.01,0 01/09/89,0.01,0 01/10/89,-0.01,0 01/11/89,-0.03,0 01/12/89,-0.02,0 01/01/90,-0.02,0 01/02/90,0,0 01/03/90,0.01,0 01/04/90,0.04,0 01/05/90,-0.01,0 01/06/90,0.01,0 01/07/90,-0.02,0 01/08/90,-0.05,0 01/09/90,0,0 01/10/90,-0.01,0 01/11/90,-0.03,0 01/12/90,0.02,0 01/01/91,-0.01,0 01/02/91,-0.03,0 01/03/91,0.04,0 01/04/91,0.05,0 01/05/91,0.01,0 01/06/91,0.04,0 01/07/91,0.01,0 01/08/91,-0.02,0 01/09/91,-0.02,0 01/10/91,-0.02,0 01/11/91,-0.04,0 01/12/91,0.02,0 01/01/92,-0.05,0 01/02/92,-0.01,0 01/03/92,0.01,0 01/04/92,-0.04,0 01/05/92,-0.08,0 01/06/92,0,0 01/07/92,-0.08,0 01/08/92,-0.08,0 01/09/92,0.04,0 01/10/92,0.02,0 01/11/92,0.04,0 01/12/92,0.06,0 01/01/93,0,0 01/02/93,0,0 01/03/93,0.04,0 01/04/93,-0.05,0 01/05/93,0.08,0 01/06/93,0.04,0 01/07/93,0.05,0 01/08/93,0,0 01/09/93,0,0 01/10/93,-0.09,0 01/11/93,-0.03,0 01/12/93,-0.09,0 01/01/94,0.01,0 01/02/94,0.02,0 01/03/94,0.05,0 01/04/94,0.07,0 01/05/94,0.07,0 01/06/94,-0.01,0 01/07/94,-0.03,0 01/08/94,-0.08,0 01/09/94,0.06,0 01/10/94,-0.03,0 01/11/94,0.01,0 01/12/94,0,0 01/01/95,-0.01,0 01/02/95,0.02,0 01/03/95,0,0 01/04/95,0.07,0 01/05/95,-0.03,0 01/06/95,0.02,0 01/07/95,-0.01,0 01/08/95,0,0 01/09/95,0.01,0 01/10/95,-0.02,0 01/11/95,-0.03,0 01/12/95,0,0 01/01/96,-0.01,0 01/02/96,0.05,1 01/03/96,0.08,1 01/04/96,0.16,1 01/05/96,0.1,1 01/06/96,-0.07,1 01/07/96,0.03,1 01/08/96,0.06,1 01/09/96,-0.05,1 01/10/96,0.01,1 01/11/96,0.03,0 01/12/96,0.04,0 01/01/97,-0.07,0 01/02/97,-0.06,0 01/03/97,-0.02,0 01/04/97,-0.02,0 01/05/97,-0.1,0 01/06/97,-0.01,0 01/07/97,0,0 01/08/97,-0.01,0 01/09/97,-0.01,0 01/10/97,-0.01,0 01/11/97,0.04,0 01/12/97,0.01,0 01/01/98,-0.01,0 01/02/98,-0.05,0 01/03/98,-0.04,0 01/04/98,0.01,0 01/05/98,0.1,1 01/06/98,0.2,1 01/07/98,0.25,1 01/08/98,0.1,1 01/09/98,-0.08,0 01/10/98,-0.11,0 01/11/98,-0.07,0 01/12/98,0.01,0 01/01/99,-0.02,0 01/02/99,-0.02,0 01/03/99,-0.02,0 01/04/99,-0.07,0 01/05/99,0.03,0 01/06/99,-0.06,0 01/07/99,-0.07,0 01/08/99,0,0 01/09/99,-0.06,0 01/10/99,-0.02,0 01/11/99,0,0 01/12/99,0,0 01/01/00,-0.07,0 01/02/00,0.03,0 01/03/00,0.02,0 01/04/00,0.04,0 01/05/00,0.09,0 01/06/00,-0.03,0 01/07/00,-0.01,0 01/08/00,0.01,0 01/09/00,0.03,0 01/10/00,0.04,0 01/11/00,0.02,0 01/12/00,0,0 01/01/01,0,0 01/02/01,0.01,0 01/03/01,0.02,0 01/04/01,0.03,0 01/05/01,-0.02,0 01/06/01,-0.04,1 01/07/01,-0.01,1 01/08/01,0.01,1 01/09/01,-0.01,1 01/10/01,0.06,1 01/11/01,0.04,1 01/12/01,0.21,1 01/01/02,0.02,0 01/02/02,-0.01,0 01/03/02,0.07,0 01/04/02,0.01,0 01/05/02,-0.04,0 01/06/02,-0.01,0 01/07/02,-0.01,0 01/08/02,0.07,0 01/09/02,0.04,0 01/10/02,-0.02,0 01/11/02,-0.07,0 01/12/02,-0.05,0 01/01/03,-0.03,0 01/02/03,-0.02,0 01/03/03,-0.03,0 01/04/03,-0.03,0 01/05/03,-0.06,0 01/06/03,-0.05,0 01/07/03,-0.04,0 01/08/03,-0.07,0 01/09/03,-0.09,0 01/10/03,-0.13,0 01/11/03,-0.09,0 01/12/03,0,0 01/01/04,0.06,0 01/02/04,-0.02,0 01/03/04,-0.02,0 01/04/04,-0.04,0 01/05/04,0.04,0 01/06/04,-0.05,0 01/07/04,-0.05,0 01/08/04,-0.02,0 01/09/04,0.01,0 01/10/04,-0.01,0 01/11/04,-0.07,0 01/12/04,-0.04,0 01/01/05,0.02,0 01/02/05,0,0 01/03/05,-0.02,0 01/04/05,-0.02,0 01/05/05,0.01,0 01/06/05,0.06,0 01/07/05,-0.01,0 01/08/05,-0.04,0 01/09/05,-0.01,0 01/10/05,0.03,0 01/11/05,0.02,0 01/12/05,-0.06,0 01/01/06,-0.06,0 01/02/06,-0.01,0 01/03/06,0.02,0 01/04/06,-0.02,0 01/05/06,0.04,0 01/06/06,0.13,0 01/07/06,0.07,0 01/08/06,-0.02,0 01/09/06,0.08,0 01/10/06,0.06,0 01/11/06,-0.05,0 01/12/06,-0.01,0 01/01/07,0.05,0 01/02/07,-0.04,0 01/03/07,0.01,0 01/04/07,-0.02,0 01/05/07,0.01,0 01/06/07,0.06,0 01/07/07,-0.05,0 01/08/07,0.07,0 01/09/07,0,0 01/10/07,-0.01,0 01/11/07,0.02,0 01/12/07,0.02,0 01/01/08,0,0 01/02/08,0.08,0' library(zoo) z <- read.zoo(text = Lines, format = "%d/%m/%y", sep = ",", header = TRUE, col.names = c("", "IEMP", "Distress")) plot(cbind(z$IEMP, ifelse(z$Distress, z, NA)), col = 1:2, screen = 1, ylab = "IEMP") legend("bottomright", c("Normal", "Distress"), lty = 1, col = 1:2) zoo/demo/00Index0000644000175100001440000000010511354654671013165 0ustar hornikuserszoo-overplot Plot time series in black with certain regions in red. zoo/man/0000755000175100001440000000000014415350020011644 5ustar hornikuserszoo/man/aggregate.zoo.Rd0000644000175100001440000001441013472736511014706 0ustar hornikusers \name{aggregate.zoo} \alias{aggregate.zoo} \alias{split.zoo} \title{Compute Summary Statistics of zoo Objects} \description{ Splits a \code{"zoo"} object into subsets along a coarser index grid, computes summary statistics for each, and returns the reduced \code{"zoo"} object. } \usage{ \method{aggregate}{zoo}(x, by, FUN = sum, \dots, regular = NULL, frequency = NULL, coredata = TRUE) } \arguments{ \item{x}{an object of class \code{"zoo"}.} \item{by}{index vector of the same length as \code{index(x)} which defines aggregation groups and the new index to be associated with each group. If \code{by} is a function, then it is applied to \code{index(x)} to obtain the aggregation groups.} \item{FUN}{a function to compute the summary statistics which can be applied to all subsets. Always needs to return a result of fixed length (typically scalar).} \item{\dots}{further arguments passed to \code{FUN}.} \item{regular}{logical. Should the aggregated series be coerced to class \code{"zooreg"} (if the series is regular)? The default is \code{FALSE} for \code{"zoo"} series and \code{TRUE} for \code{"zooreg"} series.} \item{frequency}{numeric indicating the frequency of the aggregated series (if a \code{"zooreg"} series should be returned. The default is to determine the frequency from the data if \code{regular} is \code{TRUE}. If \code{frequency} is specified, it sets \code{regular} to \code{TRUE}. See examples for illustration.} \item{coredata}{logical. Should only the \code{coredata(x)} be passed to every \code{by} group? If set to \code{FALSE} the full zoo series is used.} } \value{ An object of class \code{"zoo"} or \code{"zooreg"}. } \note{The \code{xts} package functions \code{endpoints}, \code{period.apply} \code{to.period}, \code{to.weekly}, \code{to.monthly}, etc., can also directly input and output certain \code{zoo} objects and so can be used for aggregation tasks in some cases as well.} \seealso{\code{\link{zoo}}} \examples{ ## averaging over values in a month: # x.date is jan 1,3,5,7; feb 9,11,13; mar 15,17,19 x.date <- as.Date(paste(2004, rep(1:4, 4:1), seq(1,20,2), sep = "-")); x.date x <- zoo(rnorm(12), x.date); x # coarser dates - jan 1 (4 times), feb 1 (3 times), mar 1 (3 times) x.date2 <- as.Date(paste(2004, rep(1:4, 4:1), 1, sep = "-")); x.date2 x2 <- aggregate(x, x.date2, mean); x2 # same - uses as.yearmon x2a <- aggregate(x, as.Date(as.yearmon(time(x))), mean); x2a # same - uses by function x2b <- aggregate(x, function(tt) as.Date(as.yearmon(tt)), mean); x2b # same - uses cut x2c <- aggregate(x, as.Date(cut(time(x), "month")), mean); x2c # almost same but times of x2d have yearmon class rather than Date class x2d <- aggregate(x, as.yearmon, mean); x2d # compare time series plot(x) lines(x2, col = 2) ## aggregate a daily time series to a quarterly series # create zoo series tt <- as.Date("2000-1-1") + 0:300 z.day <- zoo(0:300, tt) # function which returns corresponding first "Date" of quarter first.of.quarter <- function(tt) as.Date(as.yearqtr(tt)) # average z over quarters # 1. via "yearqtr" index (regular) # 2. via "Date" index (not regular) z.qtr1 <- aggregate(z.day, as.yearqtr, mean) z.qtr2 <- aggregate(z.day, first.of.quarter, mean) # The last one used the first day of the quarter but suppose # we want the first day of the quarter that exists in the series # (and the series does not necessarily start on the first day # of the quarter). z.day[!duplicated(as.yearqtr(time(z.day)))] # This is the same except it uses the last day of the quarter. # It requires R 2.6.0 which introduced the fromLast= argument. \dontrun{ z.day[!duplicated(as.yearqtr(time(z.day)), fromLast = TRUE)] } # The aggregated series above are of class "zoo" (because z.day # was "zoo"). To create a regular series of class "zooreg", # the frequency can be automatically chosen zr.qtr1 <- aggregate(z.day, as.yearqtr, mean, regular = TRUE) # or specified explicitely zr.qtr2 <- aggregate(z.day, as.yearqtr, mean, frequency = 4) ## aggregate on month and extend to monthly time series if(require(chron)) { y <- zoo(matrix(11:15, nrow = 5, ncol = 2), chron(c(15, 20, 80, 100, 110))) colnames(y) <- c("A", "B") # aggregate by month using first of month as times for coarser series # using first day of month as repesentative time y2 <- aggregate(y, as.Date(as.yearmon(time(y))), head, 1) # fill in missing months by merging with an empty series containing # a complete set of 1st of the months yrt2 <- range(time(y2)) y0 <- zoo(,seq(from = yrt2[1], to = yrt2[2], by = "month")) merge(y2, y0) } # given daily series keep only first point in each month at # day 21 or more z <- zoo(101:200, as.Date("2000-01-01") + seq(0, length = 100, by = 2)) zz <- z[as.numeric(format(time(z), "\%d")) >= 21] zz[!duplicated(as.yearmon(time(zz)))] # same except times are of "yearmon" class aggregate(zz, as.yearmon, head, 1) # aggregate POSIXct seconds data every 10 minutes Sys.setenv(TZ = "GMT") tt <- seq(10, 2000, 10) x <- zoo(tt, structure(tt, class = c("POSIXt", "POSIXct"))) aggregate(x, time(x) - as.numeric(time(x)) \%\% 600, mean) # aggregate weekly series to a series with frequency of 52 per year suppressWarnings(RNGversion("3.5.0")) set.seed(1) z <- zooreg(1:100 + rnorm(100), start = as.Date("2001-01-01"), deltat = 7) # new.freq() converts dates to a grid of freq points per year # yd is sequence of dates of firsts of years # yy is years of the same sequence # last line interpolates so dates, d, are transformed to year + frac of year # so first week of 2001 is 2001.0, second week is 2001 + 1/52, third week # is 2001 + 2/52, etc. new.freq <- function(d, freq = 52) { y <- as.Date(cut(range(d), "years")) + c(0, 367) yd <- seq(y[1], y[2], "year") yy <- as.numeric(format(yd, "\%Y")) floor(freq * approx(yd, yy, xout = d)$y) / freq } # take last point in each period aggregate(z, new.freq, tail, 1) # or, take mean of all points in each aggregate(z, new.freq, mean) # example of taking means in the presence of NAs z.na <- zooreg(c(1:364, NA), start = as.Date("2001-01-01")) aggregate(z.na, as.yearqtr, mean, na.rm = TRUE) # Find the sd of all days that lie in any Jan, all days that lie in # any Feb, ..., all days that lie in any Dec (i.e. output is vector with # 12 components) aggregate(z, format(time(z), "\%m"), sd) } \keyword{ts} zoo/man/coredata.Rd0000755000175100001440000000251613472624404013740 0ustar hornikusers\name{coredata} \alias{coredata} \alias{coredata.default} \alias{coredata.zoo} \alias{coredata.ts} \alias{coredata.its} \alias{coredata.irts} \alias{coredata<-} \alias{coredata<-.zoo} \alias{coredata<-.ts} \alias{coredata<-.irts} \alias{coredata<-.its} \title{Extracting/Replacing the Core Data of Objects} \description{ Generic functions for extracting the core data contained in a (more complex) object and replacing it. } \usage{ coredata(x, \dots) coredata(x) <- value } \arguments{ \item{x}{an object.} \item{\dots}{further arguments passed to methods.} \item{value}{a suitable value object for use with \code{x}.} } \value{ In \code{zoo}, there are currently \code{coredata} methods for time series objects of class \code{"zoo"}, \code{"ts"}, \code{"its"}, \code{"irts"}, all of which strip off the index/time attributes and return only the observations. The are also corresponding replacement methods for these classes. } \seealso{\code{\link{zoo}}} \examples{ suppressWarnings(RNGversion("3.5.0")) set.seed(1) x.date <- as.Date(paste(2003, rep(1:4, 4:1), seq(1,20,2), sep = "-")) x <- zoo(matrix(rnorm(20), ncol = 2), x.date) ## the full time series x ## and only matrix of observations coredata(x) ## change the observations coredata(x) <- matrix(1:20, ncol = 2) x } \keyword{ts} zoo/man/plot.zoo.Rd0000644000175100001440000003123413777333215013743 0ustar hornikusers\name{plot.zoo} \alias{plot.zoo} \alias{barplot.zoo} \alias{boxplot.zoo} \alias{lines.zoo} \alias{points.zoo} \title{Plotting zoo Objects} \description{ Plotting method for objects of class \code{"zoo"}. } \usage{ \method{plot}{zoo}(x, y = NULL, screens, plot.type, panel = lines, xlab = "Index", ylab = NULL, main = NULL, xlim = NULL, ylim = NULL, xy.labels = FALSE, xy.lines = NULL, yax.flip = FALSE, oma = c(6, 0, 5, 0), mar = c(0, 5.1, 0, if(yax.flip) 5.1 else 2.1), col = 1, lty = 1, lwd = 1, pch = 1, type = "l", log = "", nc, widths = 1, heights = 1, \dots) \method{lines}{zoo}(x, y = NULL, type = "l", \dots) \method{points}{zoo}(x, y = NULL, type = "p", \dots) } \arguments{ \item{x}{an object of class \code{"zoo"}.} \item{y}{an object of class \code{"zoo"}. If \code{y} is \code{NULL} (the default) a time series plot of \code{x} is produced, otherwise if both \code{x} and \code{y} are univariate \code{"zoo"} series, a scatter plot of \code{y} versus \code{x} is produced.} \item{screens}{factor (or coerced to factor) whose levels specify which graph each series is to be plotted in. \code{screens=c(1,2,1)} would plot series 1, 2 and 3 in graphs 1, 2 and 1. If not specified then 1 is used if \code{plot.type="single"} and \code{seq_len(ncol(x))} otherwise.} \item{plot.type}{for multivariate zoo objects, "multiple" plots the series on multiple plots and "single" superimposes them on a single plot. Default is "single" if \code{screens} has only one level and \code{"multiple"} otherwise. If neither \code{screens} nor \code{plot.type} is specified then \code{"single"} is used if there is one series and \code{"mulitple"} otherwise. This option is provided for back compatibility. Usually \code{screens} is used instead.} \item{panel}{a \code{function(x, y, col, lty, \dots)} which gives the action to be carried out in each panel of the display for \code{plot.type = "multiple"}.} \item{ylim}{if \code{plot.type = "multiple"} then it can be a list of y axis limits. If not a list each graph has the same limits. If any list element is not a pair then its range is used instead. If \code{plot.type = "single"} then it is as in \code{plot}.} \item{xy.labels}{logical, indicating if \code{\link{text}} labels should be used in the scatter plot, or character, supplying a vector of labels to be used.} \item{xy.lines}{logical, indicating if \code{\link{lines}} should be drawn in the scatter plot. Defaults to the value of \code{xy.labels} if that is logical, otherwise to \code{FALSE}.} \item{yax.flip}{logical, indicating if the y-axis (ticks and numbering) should flip from side 2 (left) to 4 (right) from series to series when \code{type = "multiple"}.} \item{xlab, ylab, main, xlim, oma, mar}{graphical arguments, see \code{\link{par}}.} \item{col, lty, lwd, pch, type}{graphical arguments that can be vectors or (named) lists. See the details for more information.} \item{log}{specification of log scales as \code{"x"}, \code{"y"} or \code{"xy"}.} \item{nc}{the number of columns to use when \code{plot.type = "multiple"}. Defaults to \code{1} for up to \code{4} series, otherwise to \code{2}.} \item{widths, heights}{widths and heights for individual graphs, see \code{\link{layout}}.} \item{\dots}{additional graphical arguments.} } \details{ The methods for \code{plot} and \code{lines} are very similar to the corresponding \code{ts} methods. However, the handling of several graphical parameters is more flexible for multivariate series. These parameters can be vectors of the same length as the number of series plotted or are recycled if shorter. They can also be (partially) named list, e.g., \code{list(A = c(1,2), c(3,4))} in which \code{c(3, 4)} is the default value and \code{c(1, 2)} the value only for series \code{A}. The \code{screens} argument can be specified in a similar way. If \code{plot.type} and \code{screens} conflict then multiple plots will be assumed. Also see the examples. In the case of a custom panel the panel can reference \code{parent.frame$panel.number} in order to determine which frame the panel is being called from. See examples. \code{par(mfrow=...)} and \code{Axis} can be used in conjunction with single panel plots in the same way as with other classic graphics. For multi-panel graphics, \code{plot.zoo} takes over the layout so \code{par(mfrow=...)} cannot be used. \code{Axis} can be used within the panels themselves but not outside the panel. See examples. Also, \code{par(new = TRUE)} is not supported for multi-panel graphics. In addition to classical time series line plots, there is also a simple \code{\link{barplot}} method for \code{"zoo"} series. Additionally, there is a \code{\link{boxplot}} method that visualizes the \code{coredata} of the \code{"zoo"} series with a box plot. } \seealso{\code{\link{zoo}}, \code{\link{plot.ts}}, \code{\link{barplot}}, \code{\link{boxplot}}, \code{\link{xyplot.zoo}}} \examples{ ## example dates x.Date <- as.Date(paste(2003, 02, c(1, 3, 7, 9, 14), sep = "-")) ## univariate plotting x <- zoo(rnorm(5), x.Date) x2 <- zoo(rnorm(5, sd = 0.2), x.Date) plot(x) lines(x2, col = 2) ## multivariate plotting z <- cbind(x, x2, zoo(rnorm(5, sd = 0.5), x.Date)) plot(z, type = "b", pch = 1:3, col = 1:3, ylab = list(expression(mu), "b", "c")) colnames(z) <- LETTERS[1:3] plot(z, screens = 1, col = list(B = 2)) plot(z, type = "b", pch = 1:3, col = 1:3) plot(z, type = "b", pch = list(A = 1:5, B = 3), col = list(C = 4, 2)) plot(z, type = "b", screen = c(1,2,1), col = 1:3) # right axis is for broken lines plot(x) opar <- par(usr = c(par("usr")[1:2], range(x2))) lines(x2, lty = 2) # axis(4) axis(side = 4) par(opar) ## Custom x axis labelling using a custom panel. # 1. test data z <- zoo(c(21, 34, 33, 41, 39, 38, 37, 28, 33, 40), as.Date(c("1992-01-10", "1992-01-17", "1992-01-24", "1992-01-31", "1992-02-07", "1992-02-14", "1992-02-21", "1992-02-28", "1992-03-06", "1992-03-13"))) zz <- merge(a = z, b = z+10) # 2. axis tick for every point. Also every 3rd point labelled. my.panel <- function(x, y, ..., pf = parent.frame()) { fmt <- "\%b-\%d" # format for axis labels lines(x, y, ...) # if bottom panel if (with(pf, length(panel.number) == 0 || panel.number \%\% nr == 0 || panel.number == nser)) { # create ticks at x values and then label every third tick axis(side = 1, at = x, labels = FALSE) ix <- seq(1, length(x), 3) labs <- format(x, fmt) axis(side = 1, at = x[ix], labels = labs[ix], tcl = -0.7, cex.axis = 0.7) } } # 3. plot plot(zz, panel = my.panel, xaxt = "n") # with a single panel plot a fancy x-axis is just the same # procedure as for the ordinary plot command plot(zz, screen = 1, col = 1:2, xaxt = "n") # axis(1, at = time(zz), labels = FALSE) tt <- time(zz) axis(side = 1, at = tt, labels = FALSE) ix <- seq(1, length(tt), 3) fmt <- "\%b-\%d" # format for axis labels labs <- format(tt, fmt) # axis(1, at = time(zz)[ix], labels = labs[ix], tcl = -0.7, cex.axis = 0.7) axis(side = 1, at = tt[ix], labels = labs[ix], tcl = -0.7, cex.axis = 0.7) legend("bottomright", colnames(zz), lty = 1, col = 1:2) ## plot a mulitple ts series with nice x-axis using panel function tab <- ts(cbind(A = 1:24, B = 24:1), start = c(2006, 1), freq = 12) pnl.xaxis <- function(...) { lines(...) panel.number <- parent.frame()$panel.number nser <- parent.frame()$nser # if bottom panel if (!length(panel.number) || panel.number == nser) { tt <- list(...)[[1]] ym <- as.yearmon(tt) mon <- as.numeric(format(ym, "\%m")) yy <- format(ym, "\%y") mm <- substring(month.abb[mon], 1, 1) if (any(mon == 1)) # axis(1, tt[mon == 1], yy[mon == 1], cex.axis = 0.7) axis(side = 1, at = tt[mon == 1], labels = yy[mon == 1], cex.axis = 0.7) # axis(1, tt[mon > 1], mm[mon > 1], cex.axis = 0.5, tcl = -0.3) axis(side = 1, at = tt[mon > 1], labels = mm[mon > 1], cex.axis = 0.5, tcl = -0.3) } } plot(as.zoo(tab), panel = pnl.xaxis, xaxt = "n", main = "Fancy X Axis") ## Another example with a custom axis # test data z <- zoo(matrix(1:25, 5), c(10,11,20,21)) colnames(z) <- letters[1:5] plot(zoo(coredata(z)), xaxt = "n", panel = function(x, y, ..., Time = time(z)) { lines(x, y, ...) # if bottom panel pf <- parent.frame() if (with(pf, panel.number \%\% nr == 0 || panel.number == nser)) { axis(side = 1, at = x, labels = Time) } }) ## plot with left and right axes ## modified from http://www.mayin.org/ajayshah/KB/R/html/g6.html suppressWarnings(RNGversion("3.5.0")) set.seed(1) z <- zoo(cbind(A = cumsum(rnorm(100)), B = cumsum(rnorm(100, mean = 0.2)))) opar <- par(mai = c(.8, .8, .2, .8)) plot(z[,1], type = "l", xlab = "x-axis label", ylab = colnames(z)[1]) par(new = TRUE) plot(z[,2], type = "l", ann = FALSE, yaxt = "n", col = "blue") # axis(4) axis(side = 4) legend(x = "topleft", bty = "n", lty = c(1,1), col = c("black", "blue"), legend = paste(colnames(z), c("(left scale)", "(right scale)"))) usr <- par("usr") # if you don't care about srt= in text then mtext is shorter: # mtext(colnames(z)[2], 4, 2, col = "blue") text(usr[2] + .1 * diff(usr[1:2]), mean(usr[3:4]), colnames(z)[2], srt = -90, xpd = TRUE, col = "blue") par(opar) ## another plot with left and right axes ## modified from https://stat.ethz.ch/pipermail/r-help/2014-May/375293.html d1 <- c(38.2, 18.1, 83.2, 42.7, 22.8, 48.1, 81.8, 129.6, 52.0, 110.3) d2 <- c(2.2, 0.8, 0.7, 1.6, 0.9, 0.9, 1.1, 2.8, 5.1, 2.1) z1 <- zooreg(d1, start = as.POSIXct("2013-01-01 00:00:01"), frequency = 0.0000006) z2 <- zooreg(d2, start = as.POSIXct("2013-01-01 00:00:20"), frequency = 0.0000006) zt <- zooreg(rnorm(1050), start = as.POSIXct("2013-01-01 00:00:01"), frequency = 0.00007) z <- merge(zt, z1, z2, all = TRUE) z <- na.spline(z[,2:3], na.rm = FALSE) ## function to round up to a number divisible by n (2011 by Owen Jones) roundup <- function(x, n) ceiling(ceiling(x)/n) * n ## plot how to match secondary y-axis ticks to primary ones plot(z$z1, ylim = c(0, signif(max(na.omit(z$z1)), 2)), xlab = "") ## use multiplication for even tick numbers and fake sekondary y-axis max.yl <- roundup(max(na.omit(z$z2)), par("yaxp")[3]) multipl.yl <- max(na.omit(z$z2)) / max.yl multipl.z2 <- signif(max(na.omit(z$z1) * 1.05), 2)/max.yl lines(z$z2 * multipl.z2, lty = 2) at4 <- axTicks(4) axis(4, at = at4, seq(0, max.yl, length.out = par("yaxp")[3] + 1)) # automatically placed point labels \dontrun{ library("maptools") pointLabel(time(z), coredata(z[,2]), labels = format(time(z)), cex = 0.5) } ## plot one zoo series against the other. plot(x, x2) plot(x, x2, xy.labels = TRUE) plot(x, x2, xy.labels = 1:5, xy.lines = FALSE) ## shade a portion of a plot and make axis fancier v <- zooreg(rnorm(50), start = as.yearmon(2004), freq = 12) plot(v, type = "n") u <- par("usr") rect(as.yearmon("2007-8"), u[3], as.yearmon("2009-11"), u[4], border = 0, col = "grey") lines(v) axis(1, floor(time(v)), labels = FALSE, tcl = -1) ## shade certain times to show recessions, etc. v <- zooreg(rnorm(50), start = as.yearmon(2004), freq = 12) plot(v, type = "n") u <- par("usr") rect(as.yearmon("2007-8"), u[3], as.yearmon("2009-11"), u[4], border = 0, col = "grey") lines(v) axis(1, floor(time(v)), labels = FALSE, tcl = -1) ## fill area under plot pnl.xyarea <- function(x, y, fill.base = 0, col = 1, ...) { lines(x, y, ...) panel.number <- parent.frame()$panel.number col <- rep(col, length = panel.number)[panel.number] polygon(c(x[1], x, tail(x, 1), x[1]), c(fill.base, as.numeric(y), fill.base, fill.base), col = col) } plot(zoo(EuStockMarkets), col = rainbow(4), panel = pnl.xyarea) ## barplot x <- zoo(cbind(rpois(5, 2), rpois(5, 3)), x.Date) barplot(x, beside = TRUE) ## boxplot boxplot(x) ## 3d plot ## The persp function in R (not part of zoo) works with zoo objects. ## The following example is by Enrico Schumann. ## https://stat.ethz.ch/pipermail/r-sig-finance/2009q1/003710.html nC <- 10 # columns nO <- 100 # observations dataM <- array(runif(nC * nO), dim=c(nO, nC)) zz <- zoo(dataM, 1:nO) persp(1:nO, 1:nC, zz) # interactive plotting \dontrun{ library("TeachingDemos") tke.test1 <- list(Parameters = list( lwd = list("spinbox", init = 1, from = 0, to = 5, increment = 1, width = 5), lty = list("spinbox", init = 1, from = 0, to = 6, increment = 1, width = 5) )) z <- zoo(rnorm(25)) tkexamp(plot(z), tke.test1, plotloc = "top") } # setting ylim on a multi-panel plot - 2nd panel y axis range is 1-50 data("anscombe", package = "datasets") ans6 <- zoo(anscombe[, 1:6]) screens <- c(1, 1, 2, 2, 3, 3) ylim <- unname(tapply(as.list(ans6), screens, range)) ylim[[2]] <- 1:50 # or ylim[[2]] <- c(1, 50) plot(ans6, screens = screens, ylim = ylim) } \keyword{ts} zoo/man/na.fill.Rd0000644000175100001440000000356313272327044013477 0ustar hornikusers\name{na.fill} \alias{na.fill} \alias{na.fill0} \alias{na.fill.ts} \alias{na.fill.zoo} \alias{na.fill.default} \title{Fill NA or specified positions.} \description{ Generic function for filling \code{NA} values or specified positions. } \usage{ na.fill(object, fill, \dots) \method{na.fill}{ts}(object, fill, ix, \dots) \method{na.fill}{zoo}(object, fill, ix, \dots) \method{na.fill}{default}(object, fill, ix, \dots) na.fill0(object, fill, ix = !is.na(object)) } \arguments{ \item{object}{an object.} \item{fill}{a three component list or a vector that is coerced to a list. Shorter objects are recycled. The three components represent the fill value to the left of the data, within the interior of the data and to the right of the data, respectively. The value of any component may be the keyword \code{"extend"} to indicate repetition of the leftmost or rightmost non-NA value or linear interpolation in the interior. \code{NULL} means that items are dropped rather than filled.} \item{ix}{logical. Should be the same length as the number of time points. Indicates which time points not to fill. This defaults to the non-NA values.} \item{\dots}{further arguments passed to methods.} } \details{ \code{na.fill} is a generic function for filling \code{NA} or indicated values. It currently has methods for the time series classes \code{"zoo"} and \code{"ts"} and a default method based on the \code{"zoo"} method. Furthermore, \code{na.fill0} works with plain vectors and \code{"Date"} objects. It also works with \code{"zoo"} objects provided that no \code{fill} component is \code{NULL}. } \seealso{\code{\link{na.approx}}} \examples{ z <- zoo(c(NA, 2, NA, 1, 4, 5, 2, NA)) na.fill(z, "extend") na.fill(z, c("extend", NA)) na.fill(z, -(1:3)) na.fill(z, list(NA, NULL, NA)) } \keyword{ts} zoo/man/na.trim.Rd0000644000175100001440000000315513444026012013511 0ustar hornikusers\name{na.trim} \alias{na.trim} \alias{na.trim.default} \alias{na.trim.ts} \title{Trim Leading/Trailing Missing Observations} \description{ Generic function for removing leading and trailing \code{NA}s. } \usage{ na.trim(object, \dots) \method{na.trim}{default}(object, sides = c("both", "left", "right"), is.na = c("any", "all"), maxgap = Inf, \dots) } \arguments{ \item{object}{an object.} \item{sides}{character specifying whether \code{NA}s are to be removed from both sides, just from the left side or just from the right side.} \item{is.na}{If "any" then a row will be regarded as \code{NA} if it has any \code{NA}s. If "all" then a row will be regarded as \code{NA} only if all elements in the row are \code{NA}. For one dimensional zoo objects this argument has no effect.} \item{maxgap}{maximum number of consecutive \code{NA}s to trim. Any longer gaps will be left unchanged.} \item{\dots}{further arguments passed to methods.} } \value{ An object in which leading and/or trailing \code{NA}s have been removed. } \seealso{\code{\link{na.approx}}, \code{\link{na.contiguous}}, \code{\link{na.locf}}, \code{\link{na.omit}}, \code{\link{na.spline}}, \code{\link[stinepack]{stinterp}}, \code{\link{zoo}}} \examples{ # examples of na.trim x <- zoo(c(1, 4, 6), c(2, 4, 6)) xx <- zoo(matrix(c(1, 4, 6, NA, 5, 7), 3), c(2, 4, 6)) na.trim(x) na.trim(xx) # using na.trim for alignment # cal defines the legal dates # all dates within the date range of x should be present cal <- zoo(,c(1, 2, 3, 6, 7)) x <- zoo(c(12, 16), c(2, 6)) na.trim(merge(x, cal)) } \keyword{ts} zoo/man/as.zoo.Rd0000644000175100001440000000434314300524166013357 0ustar hornikusers\name{as.zoo} \alias{as.zoo} \alias{as.zoo.default} \alias{as.zoo.data.frame} \alias{as.zoo.fts} \alias{as.zoo.its} \alias{as.zoo.irts} \alias{as.zoo.matrix} \alias{as.zoo.mcmc} \alias{as.zoo.tis} \alias{as.zoo.xts} \alias{as.zoo.zoo} \alias{as.matrix.zoo} \alias{as.vector.zoo} \alias{as.data.frame.zoo} \alias{as.list.zoo} \alias{as.list.ts} \alias{as.zoo.ts} \alias{as.ts.zoo} \title{Coercion from and to zoo} \description{ Methods for coercing \code{"zoo"} objects to other classes and a generic function \code{as.zoo} for coercing objects to class \code{"zoo"}. } \usage{ as.zoo(x, \dots) } \arguments{ \item{x}{an object,} \item{\dots}{further arguments passed to \code{\link{zoo}} when the return object is created.} } \details{ \code{as.zoo} currently has a default method and methods for \code{\link{ts}}, \code{fts} (currently archived on CRAN), \code{\link[tseries]{irts}}, \code{\link[coda]{mcmc}}, \code{\link[tis]{tis}}, \code{\link[xts]{xts}} objects (and \code{\link{zoo}} objects themselves). Methods for coercing objects of class \code{"zoo"} to other classes currently include: \code{\link{as.ts}}, \code{\link{as.matrix}}, \code{\link{as.vector}}, \code{\link{as.data.frame}}, \code{\link{as.list}} (the latter also being available for \code{"ts"} objects). Furthermore, \code{\link{fortify.zoo}} can transform \code{"zoo"} series to \code{"data.frame"} including the time index and optionally melting a wide series into a long data frame. In the conversion between \code{zoo} and \code{ts}, the \code{\link{zooreg}} class is always used. } \value{ \code{as.zoo} returns a \code{\link{zoo}} object. } \seealso{\code{\link{zoo}}, \code{\link{fortify.zoo}}, \code{\link{zooreg}}, \code{\link{ts}}, \code{\link[tseries]{irts}}, \code{\link[tis]{tis}}, \code{\link[coda]{mcmc}}, \code{\link[xts]{xts}}. } \examples{ suppressWarnings(RNGversion("3.5.0")) set.seed(1) ## coercion to zoo: ## default method as.zoo(rnorm(5)) ## method for "ts" objects as.zoo(ts(rnorm(5), start = 1981, freq = 12)) ## coercion from zoo: x.date <- as.POSIXct(paste("2003-", rep(1:4, 4:1), "-", sample(1:28, 10, replace = TRUE), sep = "")) x <- zoo(matrix(rnorm(24), ncol = 2), x.date) as.matrix(x) as.vector(x) as.data.frame(x) as.list(x) } \keyword{ts} zoo/man/MATCH.Rd0000644000175100001440000000313614306503712013001 0ustar hornikusers\name{MATCH} \alias{MATCH} \alias{MATCH.default} \alias{MATCH.times} \alias{MATCH.timeDate} \alias{MATCH.Date} \alias{MATCH.POSIXct} \alias{MATCH.POSIXlt} \title{Value Matching} \description{ \code{MATCH} is a generic function for value matching. } \usage{ MATCH(x, table, nomatch = NA, \dots) \method{MATCH}{times}(x, table, nomatch = NA, units = "sec", eps = 1e-10, \dots) } \arguments{ \item{x}{an object.} \item{table}{the values to be matched against.} \item{nomatch}{the value to be returned in the case when no match is found. Note that it is coerced to \code{integer}.} \item{units}{See \code{\link[chron]{trunc.times}}.} \item{eps}{See \code{\link[chron]{trunc.times}}.} \item{\dots}{further arguments to be passed to methods.} } \details{ \code{MATCH} is a new generic function which aims at providing the functionality of the non-generic base function \code{\link[base]{match}} for arbitrary objects. Currently, there is a default method which simply calls \code{\link[base]{match}} and various methods for time/date objects. The \code{MATCH} method for \code{Date} objects coerces the \code{table} to \code{Date} as well (if necessary) and then uses \code{match(unclass(x), unclass(table), ...}. Similarly, the \code{MATCH} methods for \code{POSIXct}, \code{POSIXlt}, and \code{timeDate} coerce both \code{x} and \code{table} to \code{POSIXct} and then match the unclassed objects. \code{MATCH.times} is used for \code{chron} objects. \code{x} will match any time in \code{table} less than \code{units} away. } \seealso{\code{\link[base]{match}}} \examples{ MATCH(1:5, 2:3) } \keyword{manip} zoo/man/zoo.Rd0000644000175100001440000004036614415347317012772 0ustar hornikusers\name{zoo} \alias{zoo} \alias{with.zoo} \alias{range.zoo} \alias{print.zoo} \alias{as.zoo.factor} \alias{summary.zoo} \alias{str.zoo} \alias{is.zoo} \alias{[.zoo} \alias{[<-.zoo} \alias{$.zoo} \alias{$<-.zoo} \alias{subset.zoo} \alias{head.zoo} \alias{tail.zoo} \alias{Ops.zoo} \alias{t.zoo} \alias{cumsum.zoo} \alias{cumprod.zoo} \alias{cummin.zoo} \alias{cummax.zoo} \alias{mean.zoo} \alias{median.zoo} \alias{na.contiguous} \alias{na.contiguous.data.frame} \alias{na.contiguous.list} \alias{na.contiguous.default} \alias{na.contiguous.zoo} \alias{scale.zoo} \alias{xtfrm.zoo} \alias{names.zoo} \alias{names<-.zoo} \alias{quantile.zoo} \alias{rev.zoo} \alias{transform.zoo} \alias{ifelse.zoo} \alias{dim<-.zoo} \alias{index2char} \alias{index2char.default} \alias{index2char.numeric} \alias{index2char.POSIXt} \alias{head.ts} \alias{tail.ts} \title{Z's Ordered Observations} \description{ \code{zoo} is the creator for an S3 class of indexed totally ordered observations which includes irregular time series. } \usage{ zoo(x = NULL, order.by = index(x), frequency = NULL, calendar = getOption("zoo.calendar", TRUE)) \method{print}{zoo}(x, style = , quote = FALSE, \dots) } \arguments{ \item{x}{a numeric vector, matrix or a factor.} \item{order.by}{an index vector with unique entries by which the observations in \code{x} are ordered. See the details for support of non-unique indexes.} \item{frequency}{numeric indicating frequency of \code{order.by}. If specified, it is checked whether \code{order.by} and \code{frequency} comply. If so, a regular \code{"zoo"} series is returned, i.e., an object of class \code{c("zooreg", "zoo")}. See below and \code{\link{zooreg}} for more details.} \item{calendar}{logical. If \code{frequency} is specified and is 4 or 12: Should \code{\link{yearqtr}} or \code{\link{yearmon}} be used for a numeric index \code{order.by}?} \item{style}{a string specifying the printing style which can be \code{"horizontal"} (the default for vectors), \code{"vertical"} (the default for matrices) or \code{"plain"} (which first prints the data and then the index).} \item{quote}{logical. Should characters be quoted?} \item{\dots}{further arguments passed to the print methods of the data and the index.} } \details{ \code{zoo} provides infrastructure for ordered observations which are stored internally in a vector or matrix with an index attribute (of arbitrary class, see below). The index must have the same length as \code{NROW(x)} except in the case of a zero length numeric vector in which case the index length can be any length. Emphasis has been given to make all methods independent of the index/time class (given in \code{order.by}). In principle, the data \code{x} could also be arbitrary, but currently there is only support for vectors and matrices and partial support for factors. \code{zoo} is particularly aimed at irregular time series of numeric vectors/matrices, but it also supports regular time series (i.e., series with a certain \code{frequency}). \code{zoo}'s key design goals are independence of a particular index/date/time class and consistency with \code{ts} and base \R by providing methods to standard generics. Therefore, standard functions can be used to work with \code{"zoo"} objects and memorization of new commands is reduced. When creating a \code{"zoo"} object with the function \code{zoo}, the vector of indexes \code{order.by} can be of (a single) arbitrary class (if \code{x} is shorter or longer than \code{order.by} it is expanded accordingly), but it is essential that \code{ORDER(order.by)} works. For other functions it is assumed that \code{c()}, \code{length()}, \code{MATCH()} and subsetting \code{[,} work. If this is not the case for a particular index/date/time class, then methods for these generic functions should be created by the user. Note, that to achieve this, new generic functions \code{\link{ORDER}} and \code{\link{MATCH}} are created in the \code{zoo} package with default methods corresponding to the non-generic base functions \code{\link[base]{order}} and \code{\link[base]{match}}. Note that the \code{\link[base]{order}} and hence the default \code{\link{ORDER}} typically work if there is a \code{\link[base]{xtfrm}} method. Furthermore, for certain (but not for all) operations the index class should have an \code{as.numeric} method (in particular for regular series) and an \code{as.character} method might improve printed output (see also below). The index observations \code{order.by} should typically be unique, such that the observations can be totally ordered. Nevertheless, \code{zoo()} is able to create \code{"zoo"} objects with duplicated indexes (with a warning) and simple methods such as \code{plot()} or \code{summary()} will typically work for such objects. However, this is not formally supported as the bulk of functionality provided in \pkg{zoo} requires unique index observations/time stamps. See below for an example how to remove duplicated indexes. If a \code{frequency} is specified when creating a series via \code{zoo}, the object returned is actually of class \code{"zooreg"} which inherits from \code{"zoo"}. This is a subclass of \code{"zoo"} which relies on having a \code{"zoo"} series with an additional \code{"frequency"} attribute (which has to comply with the index of that series). Regular \code{"zooreg"} series can also be created by \code{\link{zooreg}}, the \code{zoo} analogue of \code{\link{ts}}. See the respective help page and \code{\link{is.regular}} for further details. Methods to standard generics for \code{"zoo"} objects currently include: \code{print} (see above), \code{summary}, \code{str}, \code{head}, \code{tail}, \code{[} (subsetting), \code{rbind}, \code{cbind}, \code{merge} (see \code{\link{merge.zoo}}), \code{aggregate} (see \code{\link{aggregate.zoo}}), \code{rev}, \code{split} (see \code{\link{aggregate.zoo}}), \code{barplot}, \code{plot} and \code{lines} (see \code{\link{plot.zoo}}). For multivariate \code{"zoo"} series with column names the \code{$} extractor is available, behaving similar as for \code{"data.frame"} objects. Methods are also available for \code{median} and \code{quantile}. \code{ifelse.zoo} is not a method (because \code{ifelse} is not a generic) but must be written out including the \code{.zoo} suffix. To \dQuote{prettify} printed output of \code{"zoo"} series the generic function \code{index2char} is used for turning index values into character values. It defaults to using \code{as.character} but can be customized if a different printed display should be used (although this should not be necessary, usually). The subsetting method \code{[} work essentially like the corresponding functions for vectors or matrices respectively, i.e., takes indexes of type \code{"numeric"}, \code{"integer"} or \code{"logical"}. But additionally, it can be used to index with observations from the index class of the series. If the index class of the series is one of the three classes above, the corresponding index has to be encapsulated in \code{I()} to enforce usage of the index class (see examples). Subscripting by a zoo object whose data contains logical values is undefined. Additionally, \code{zoo} provides several generic functions and methods to work (a) on the data contained in a \code{"zoo"} object, (b) the index (or time) attribute associated to it, and (c) on both data and index: (a) The data contained in \code{"zoo"} objects can be extracted by \code{coredata} (strips off all \code{"zoo"}-specific attributes) and modified using \code{coredata<-}. Both are new generic functions with methods for \code{"zoo"} objects, see \code{\link{coredata}}. (b) The index associated with a \code{"zoo"} object can be extracted by \code{index} and modified by \code{index<-}. As the interpretation of the index as \dQuote{time} in time series applications is more natural, there are also synonymous methods \code{time} and \code{time<-}. The start and the end of the index/time vector can be queried by \code{start} and \code{end}. See \code{\link{index}}. (c) To work on both data and index/time, \code{zoo} provides methods \code{lag}, \code{diff} (see \code{\link{lag.zoo}}) and \code{window}, \code{window<-} (see \code{\link{window.zoo}}). In addition to standard group generic function (see \code{\link{Ops}}), the following mathematical operations are available as methods for \code{"zoo"} objects: transpose \code{t} which coerces to a matrix first, and \code{cumsum}, \code{cumprod}, \code{cummin}, \code{cummax} which are applied column wise. Coercion to and from \code{"zoo"} objects is available for objects of various classes, in particular \code{"ts"}, \code{"irts"} and \code{"its"} objects can be coerced to \code{"zoo"}, the reverse is available for \code{"its"} and for \code{"irts"} (the latter in package \code{tseries}). Furthermore, \code{"zoo"} objects can be coerced to vectors, matrices and lists and data frames (dropping the index/time attribute). See \code{\link{as.zoo}}. Several methods are available for \code{NA} handling in the data of \code{"zoo"} objects: \code{\link{na.aggregate}} which uses group means to fill in \code{NA} values, \code{\link{na.approx}} which uses linear interpolation to fill in \code{NA} values. \code{\link{na.contiguous}} which extracts the longest consecutive stretch of non-missing values in a \code{"zoo"} object, \code{\link{na.fill}} which uses fixed specified values to replace \code{NA} values, \code{\link{na.locf}} which replaces \code{NA}s by the last previous non-\code{NA}, \code{\link{na.omit}} which returns a \code{"zoo"} object with incomplete observations removed, \code{\link{na.spline}} which uses spline interpolation to fill in \code{NA} values and \code{\link{na.StructTS}} which uses a seasonal Kalman filter to fill in \code{NA} values, \code{\link{na.trim}} which trims runs of \code{NA}s off the beginning and end but not in the interior. Yet another \code{NA} routine can be found in the \code{stinepack} package where \code{na.stinterp} performs Stineman interpolation. A typical task to be performed on ordered observations is to evaluate some function, e.g., computing the mean, in a window of observations that is moved over the full sample period. The generic function \code{\link{rollapply}} provides this functionality for arbitrary functions and more efficient versions \code{\link{rollmean}}, \code{\link{rollmax}}, \code{\link{rollmedian}} are available for the mean, maximum and median respectively. The \pkg{zoo} package has an \code{as.Date} \code{numeric} method which is similar to the one in the core of \R except that the \code{origin} argument defaults to January 1, 1970 (whereas the one in the core of \R has no default). Note that since \code{zoo} uses date/time classes from base \R and other packages, it may inherit bugs or problems with those date/time classes. Currently, there is one such known problem with the \code{c} method for the \code{POSIXct} class in base \R: If \code{x} and \code{y} are \code{POSIXct} objects with \code{tzone} attributes, the attribute will always be dropped in \code{c(x, y)}, even if it is the same across both \code{x} and \code{y}. Although this is documented at \code{\link[base:DateTimeClasses]{c.POSIXct}}, one may want to employ a workaround as shown at \url{https://stat.ethz.ch/pipermail/r-devel/2010-August/058112.html}. } \references{ Achim Zeileis and Gabor Grothendieck (2005). \pkg{zoo}: S3 Infrastructure for Regular and Irregular Time Series. \emph{Journal of Statistical Software}, \bold{14(6)}, 1-27. URL http://www.jstatsoft.org/v14/i06/ and available as \code{vignette("zoo")}. Ajay Shah, Achim Zeileis and Gabor Grothendieck (2005). \pkg{zoo} Quick Reference. Package vignette available as \code{vignette("zoo-quickref")}. } \value{ A vector or matrix with an \code{"index"} attribute of the same dimension (\code{NROW(x)}) by which \code{x} is ordered. } \seealso{\code{\link{zooreg}}, \code{\link{plot.zoo}}, \code{\link{index}}, \code{\link{merge.zoo}}} \examples{ suppressWarnings(RNGversion("3.5.0")) set.seed(1) ## simple creation and plotting x.Date <- as.Date("2003-02-01") + c(1, 3, 7, 9, 14) - 1 x <- zoo(rnorm(5), x.Date) plot(x) time(x) ## subsetting with numeric indexes x[c(2, 4)] ## subsetting with index class x[as.Date("2003-02-01") + c(2, 8)] ## different classes of indexes/times can be used, e.g. numeric vector x <- zoo(rnorm(5), c(1, 3, 7, 9, 14)) ## subsetting with numeric indexes then uses observation numbers x[c(2, 4)] ## subsetting with index class can be enforced by I() x[I(c(3, 9))] ## visualization plot(x) ## or POSIXct y.POSIXct <- ISOdatetime(2003, 02, c(1, 3, 7, 9, 14), 0, 0, 0) y <- zoo(rnorm(5), y.POSIXct) plot(y) ## create a constant series z <- zoo(1, seq(4)[-2]) ## create a 0-dimensional zoo series z0 <- zoo(, 1:4) ## create a 2-dimensional zoo series z2 <- zoo(matrix(1:12, 4, 3), as.Date("2003-01-01") + 0:3) ## create a factor zoo object fz <- zoo(gl(2,5), as.Date("2004-01-01") + 0:9) ## create a zoo series with 0 columns z20 <- zoo(matrix(nrow = 4, ncol = 0), 1:4) ## arithmetic on zoo objects intersects them first x1 <- zoo(1:5, 1:5) x2 <- zoo(2:6, 2:6) 10 * x1 + x2 ## $ extractor for multivariate zoo series with column names z <- zoo(cbind(foo = rnorm(5), bar = rnorm(5))) z$foo z$xyz <- zoo(rnorm(3), 2:4) z ## add comments to a zoo object comment(x1) <- c("This is a very simple example of a zoo object.", "It can be recreated using this R code: example(zoo)") ## comments are not output by default but are still there x1 comment(x1) # ifelse does not work with zoo but this works # to create a zoo object which equals x1 at # time i if x1[i] > x1[i-1] and 0 otherwise (diff(x1) > 0) * x1 ## zoo series with duplicated indexes z3 <- zoo(1:8, c(1, 2, 2, 2, 3, 4, 5, 5)) plot(z3) ## remove duplicated indexes by averaging lines(aggregate(z3, index(z3), mean), col = 2) ## or by using the last observation lines(aggregate(z3, index(z3), tail, 1), col = 4) ## x1[x1 > 3] is not officially supported since ## x1 > 3 is of class "zoo", not "logical". ## Use one of these instead: x1[which(x1 > 3)] x1[coredata(x1 > 3)] x1[as.logical(x1 > 3)] subset(x1, x1 > 3) ## any class supporting the methods discussed can be used ## as an index class. Here are examples using complex numbers ## and letters as the time class. z4 <- zoo(11:15, complex(real = c(1, 3, 4, 5, 6), imag = c(0, 1, 0, 0, 1))) merge(z4, lag(z4)) z5 <- zoo(11:15, letters[1:5]) merge(z5, lag(z5)) # index values relative to 2001Q1 zz <- zooreg(cbind(a = 1:10, b = 11:20), start = as.yearqtr(2000), freq = 4) zz[] <- mapply("/", as.data.frame(zz), coredata(zz[as.yearqtr("2001Q1")])) ## even though time index must be unique zoo (and read.zoo) ## will both allow creation of such illegal objects with ## a warning (rather than ana error) to give the user a ## chance to fix them up. Extracting and replacing times ## and aggregate.zoo will still work. \dontrun{ # this gives a warning # and then creates an illegal zoo object z6 <- zoo(11:15, c(1, 1, 2, 2, 5)) z6 # fix it up by averaging duplicates aggregate(z6, identity, mean) # or, fix it up by taking last in each set of duplicates aggregate(z6, identity, tail, 1) # fix it up via interpolation of duplicate times time(z6) <- na.approx(ifelse(duplicated(time(z6)), NA, time(z6)), na.rm = FALSE) # if there is a run of equal times at end they # wind up as NAs and we cannot have NA times z6 <- z6[!is.na(time(z6))] z6 x1. <- x1 <- zoo (matrix (1:12, nrow = 3), as.Date("2008-08-01") + 0:2) colnames (x1) <- c ("A", "B", "C", "D") x2 <- zoo (matrix (1:12, nrow = 3), as.Date("2008-08-01") + 1:3) colnames (x2) <- c ("B", "C", "D", "E") both.dates = as.Date (intersect (index (t1), index (t2))) both.cols = intersect (colnames (t1), colnames (t2)) x1[both.dates, both.cols] ## there is "[.zoo" but no "[<-.zoo" however four of the following ## five examples work ## wrong ## x1[both.dates, both.cols] <- x2[both.dates, both.cols] # 4 correct alternatives # #1 window(x1, both.dates)[, both.cols] <- x2[both.dates, both.cols] # #2. restore x1 and show a different way x1 <- x1. window(x1, both.dates)[, both.cols] <- window(x2, both.dates)[, both.cols] # #3. restore x1 and show a different way x1 <- x1. x1[time(x1) %in% both.dates, both.cols] <- x2[both.dates, both.cols] # #4. restore x1 and show a different way x1 <- x1. x1[time(x1) %in% both.dates, both.cols] <- x2[time(t2) %in% both.dates, both.cols] } } \keyword{ts} zoo/man/na.StructTS.Rd0000644000175100001440000000263713214034371014277 0ustar hornikusers\name{na.StructTS} \alias{na.StructTS} \alias{na.StructTS.zoo} \alias{na.StructTS.ts} \title{Fill NA or specified positions.} \description{ Generic function for filling \code{NA} values using seasonal Kalman filter.} \usage{ na.StructTS(object, \dots) \method{na.StructTS}{ts}(object, ..., na.rm = FALSE, maxgap = Inf) \method{na.StructTS}{zoo}(object, ..., na.rm = FALSE, maxgap = Inf) } \arguments{ \item{object}{an object.} \item{\dots}{other arguments passed to methods.} \item{na.rm}{logical. Whether to remove end portions or fill them with NA.} \item{maxgap}{Runs of more than \code{maxgap} \code{NA}s are retained, other \code{NA}s are removed and the last occurrence in the resulting series prior to each time point in \code{xout} is used as that time point's output value.} } \details{ Interpolate with seasonal Kalman filter, using \code{\link[stats]{StructTS}}, followed by \code{\link[stats]{tsSmooth}}. The input object should be a regular time series and have a frequency. It is assumed the cycle length is 1.} \seealso{\code{\link[stats]{StructTS}}, \code{\link[stats]{tsSmooth}}, \code{\link{na.approx}}} \examples{ z <- zooreg(rep(10 * seq(8), each = 4) + rep(c(3, 1, 2, 4), times = 8), start = as.yearqtr(2000), freq = 4) z[25] <- NA zout <- na.StructTS(z) plot(cbind(z, zout), screen = 1, col = 1:2, type = c("l", "p"), pch = 20) } \keyword{ts} zoo/man/yearqtr.Rd0000644000175100001440000001075713472721465013655 0ustar hornikusers\name{yearqtr} \alias{yearqtr} \alias{as.yearqtr} \alias{as.yearqtr.default} \alias{as.yearqtr.numeric} \alias{as.yearqtr.integer} \alias{as.yearqtr.date} \alias{as.yearqtr.dates} \alias{as.yearqtr.Date} \alias{as.yearqtr.timeDate} \alias{as.yearqtr.jul} \alias{as.yearqtr.POSIXt} \alias{as.yearqtr.character} \alias{as.yearqtr.factor} \alias{as.yearqtr.yearqtr} \alias{as.Date.yearqtr} \alias{as.POSIXct.yearqtr} \alias{as.POSIXlt.yearqtr} \alias{as.list.yearqtr} \alias{as.numeric.yearqtr} \alias{as.character.yearqtr} \alias{as.data.frame.yearqtr} \alias{c.yearqtr} \alias{cycle.yearqtr} \alias{format.yearqtr} \alias{is.numeric.yearqtr} \alias{mean.yearqtr} \alias{print.yearqtr} \alias{range.yearqtr} \alias{summary.yearqtr} \alias{unique.yearqtr} \alias{[.yearqtr} \alias{[[.yearqtr} \alias{MATCH.yearqtr} \alias{Ops.yearqtr} \alias{Summary.yearqtr} \alias{Sys.yearqtr} \alias{-.yearqtr} \alias{xtfrm.yearqtr} \title{An Index Class for Quarterly Data} \description{ \code{"yearqtr"} is a class for representing quarterly data. } \usage{ yearqtr(x) as.yearqtr(x, \dots) \method{as.yearqtr}{character}(x, format, \dots) \method{format}{yearqtr}(x, format = "\%Y Q\%q", \dots) } \arguments{ \item{x}{for \code{yearqtr} a numeric (interpreted as being \dQuote{in years}). For \code{as.yearqtr} another date class object. For the \code{"yearqtr"} method of \code{format} an object of class \code{"yearqtr"} or if called as \code{format.yearqtr} then an object with an \code{as.yearqtr} method that can be coerced to \code{"yearqtr"}.} \item{format}{character string specifying format. For coercing to \code{"yearqtr"} from character: \code{"\%Y"} and \code{"\%q"} have to be specified. For formatting an existing \code{"yearqtr"}: \code{"\%C"}, \code{"\%Y"}, \code{"\%y"} and \code{"\%q"}, if present, are replaced with the century, year, last two digits of the year, and quarter (i.e. a number between 1 and 4), respectively.} \item{\dots}{arguments passed ot other methods.} } \details{ The \code{"yearqtr"} class is used to represent quarterly data. Internally it holds the data as year plus 0 for Quarter 1, 1/4 for Quarter 2 and so on in order that its internal representation is the same as \code{ts} class with \code{frequency = 4}. If \code{x} is not in this format it is rounded via \code{floor(4*x + .0001)/4}. \code{as.yearqtr.character} uses a default format of \code{"\%Y Q\%q"}, \code{"\%Y q\%q"} or \code{"\%Y-\%q"} according to whichever matches. \code{\%q} accepts the numbers 1-4 (possibly with leading zeros). Due to this \code{\%q} does not match to single digits only and consequently formats such as \code{as.yearqtr("Q12000", "Q\%q\%Y")} are ambiguous and do not work (i.e., result in \code{NA}). There are coercion methods available for various classes including: default coercion to \code{"yearqtr"} (which coerces to \code{"numeric"} first) and coercion from \code{"yearqtr"} to \code{"Date"} (see below), \code{"POSIXct"}, \code{"POSIXlt"}, \code{"numeric"}, \code{"character"} and \code{"jul"}. The last one is from the \code{frame} package on CRAN. There is an \code{is.numeric} method which returns \code{FALSE}. There is also a \code{date} method for \code{as.yearqtr} usable with objects created with package \code{date}. \code{Sys.yearqtr()} returns the current year/month and methods for \code{min}, \code{max} and \code{range} are defined (by defining a method for \code{Summary}). A \code{yearqtr} \code{mean} method is also defined. Certain methods support a \code{frac} argument. See \code{\link{yearmon}}. } \value{ \code{yearqtr} and \code{as.yearqtr} return the first argument converted to class \code{yearqtr}. The \code{format} method returns a character string representation of its argument first argument. } \seealso{\code{\link{yearmon}}, \code{\link{zoo}}, \code{\link{zooreg}}, \code{\link{ts}}, \code{\link{strptime}}.} \examples{ Sys.setenv(TZ = "GMT") x <- as.yearqtr(2000 + seq(0, 7)/4) x format(x, "\%Y Quarter \%q") as.yearqtr("2001 Q2") as.yearqtr("2001 q2") # same as.yearqtr("2001-2") # same # returned Date is the fraction of the way through # the period given by frac (= 0 by default) dd <- as.Date(x) format.yearqtr(dd) as.Date(x, frac = 1) as.POSIXct(x) suppressWarnings(RNGversion("3.5.0")) set.seed(1) zz <- zoo(rnorm(8), x, frequency = 4) zz as.ts(zz) } \keyword{ts} zoo/man/ggplot2.zoo.Rd0000644000175100001440000001503514415306300014325 0ustar hornikusers\name{ggplot2.zoo} \alias{autoplot.zoo} \alias{fortify.zoo} \alias{ggplot2.zoo} \alias{facet_free} \alias{yearmon_trans} \alias{yearqtr_trans} \alias{scale_x_yearmon} \alias{scale_y_yearmon} \alias{scale_x_yearqtr} \alias{scale_y_yearqtr} \alias{scale_type.yearmon} \alias{scale_type.yearqtr} \title{Convenience Functions for Plotting zoo Objects with ggplot2} \details{ Convenience interface for visualizing zoo objects with ggplot2. \code{autoplot.zoo} uses \code{fortify.zoo} (with \code{melt = TRUE}) to convert the zoo object into a data frame and then uses a suitable \code{aes()} mapping to visiualize the series. } \usage{ \method{autoplot}{zoo}(object, geom = "line", facets, \dots) \method{fortify}{zoo}(model, data, names = c("Index", "Series", "Value"), melt = FALSE, sep = NULL, \dots) facet_free(facets = Series ~ ., margins = FALSE, scales = "free_y", \dots) yearmon_trans(format = "\%b \%Y", n = 5) scale_x_yearmon(\dots, format = "\%b \%Y", n = 5) scale_y_yearmon(\dots, format = "\%b \%Y", n = 5) yearqtr_trans(format = "\%Y-\%q", n = 5) scale_x_yearqtr(\dots, format = "\%Y-\%q", n = 5) scale_y_yearqtr(\dots, format = "\%Y-\%q", n = 5) } \arguments{ \item{object}{an object of class \code{"zoo"}.} \item{geom}{character (e.g., \code{"line"}) or function (e.g., \code{\link[ggplot2]{geom_line}}) specifying which \code{geom} to use.} \item{facets}{specification of \code{facets} for \code{\link[ggplot2]{facet_grid}}. The default in the \code{autoplot} method is to use \code{facets = NULL} for univariate series and \code{facets = Series ~ .} for multivariate series.} \item{\dots}{further arguments passed to \code{\link[ggplot2]{aes}} for \code{autoplot} (e.g., \code{linetype = Series} and/or \code{shape = Series}). For \code{fortify} the arguments are not used. For the \code{scale_*_*} functions the arguments are passed on to \code{scale_*_continuous}.} \item{model}{an object of class \code{"zoo"} to be converted to a \code{"data.frame"}.} \item{data}{not used (required by generic \code{\link[ggplot2]{fortify}} method).} \item{names}{(list of) character vector(s). New names given to index/time column, series indicator (if melted), and value column (if melted). If only a subset of characters should be changed, either NAs can be used or a named vector.} \item{sep}{If specified then the Series column is split into multiple columns using sep as the split character.} \item{melt}{Should the resulting data frame be in long format (\code{melt = TRUE}) or wide format (\code{melt = FALSE}).} \item{margins}{As in \code{\link[ggplot2]{facet_grid}}.} \item{scales}{As in \code{\link[ggplot2]{facet_grid}} except it defaults to \code{"free_y"}.} \item{format}{A format acceptable to \link{format.yearmon} or \link{format.yearqtr}.} \item{n}{Approximate number of axis ticks.} } \description{ \code{fortify.zoo} takes a zoo object and converts it into a data frame (intended for ggplot2). \code{autoplot.zoo} takes a zoo object and returns a ggplot2 object. It essentially uses the mapping \code{aes(x = Time, y = Value, group = Series)} and adds \code{colour = Series} in the case of a multivariate series with \code{facets = NULL}. } \value{ \code{fortify.zoo} returns a \code{data.frame} either in long format (\code{melt = TRUE}) or in wide format (\code{melt = FALSE}). The long format has three columns: the time \code{Index}, a factor indicating the \code{Series}, and the corresponding \code{Value}. The wide format simply has the time \code{Index} plus all columns of \code{coredata(model)}. \code{autoplot.zoo} returns a \code{ggplot} object. } \author{ Trevor L. Davis \email{trevor.l.davis@gmail.com}, Achim Zeileis } \seealso{ \code{\link[ggplot2]{autoplot}}, \code{\link[ggplot2]{fortify}}, \code{\link[ggplot2]{ggplot}} } \examples{ if(require("ggplot2") && require("scales")) { suppressWarnings(RNGversion("3.5.0")) set.seed(1) ## example data x.Date <- as.Date(paste(2003, 02, c(1, 3, 7, 9, 14), sep = "-")) x <- zoo(rnorm(5), x.Date) xlow <- x - runif(5) xhigh <- x + runif(5) z <- cbind(x, xlow, xhigh) ## univariate plotting autoplot(x) ## by hand ggplot(aes(x = Index, y = Value), data = fortify(x, melt = TRUE)) + geom_line() + xlab("Index") + ylab("x") ## adding series one at a time last_plot() + geom_line(aes(x = Index, y = xlow), colour = "red", data = fortify(xlow)) ## add ribbon for high/low band ggplot(aes(x = Index, y = x, ymin = xlow, ymax = xhigh), data = fortify(x)) + geom_ribbon(fill = "darkgray") + geom_line() ## multivariate plotting in multiple or single panels autoplot(z) ## multiple without color/linetype autoplot(z, facets = Series ~ .) ## multiple with series-dependent color/linetype autoplot(z, facets = NULL) ## single with series-dependent color/linetype ## by hand with color/linetype and with/without facets ggz <- ggplot(aes(x = Index, y = Value, group = Series, colour = Series, linetype = Series), data = fortify(z, melt = TRUE)) + geom_line() + xlab("Index") + ylab("") ggz ggz + facet_grid(Series ~ .) ## variations autoplot(z, geom = "point") autoplot(z, facets = NULL) + geom_point() autoplot(z, facets = NULL) + scale_colour_grey() + theme_bw() ## for "ts" series via coercion autoplot(as.zoo(EuStockMarkets)) autoplot(as.zoo(EuStockMarkets), facets = NULL) autoplot(z) + aes(colour = NULL, linetype = NULL) + facet_grid(Series ~ ., scales = "free_y") autoplot(z) + aes(colour = NULL, linetype = NULL) + facet_free() # same z.yq <- zooreg(rnorm(50), as.yearqtr("2000-1"), freq = 4) autoplot(z.yq) ## mimic matplot data <- cbind(A = c(6, 1, NA, NA), B = c(16, 4, 1, NA), C = c(25, 7, 2, 1)) autoplot(zoo(data), facet = NULL) + geom_point() ## with different line types autoplot(zoo(data), facet = NULL) + geom_point() + aes(linetype = Series) ## illustrate just fortify() method z <- zoo(data) fortify(z) fortify(z, melt = TRUE) fortify(z, melt = TRUE, names = c("Time", NA, "Data")) fortify(z, melt = TRUE, names = c(Index = "Time")) ## with/without splitting z <- zoo(cbind(a.A = 1:2, a.B = 2:3, b.A = 3:4, c.B = 4:5)) fortify(z) fortify(z, melt = TRUE, sep = ".", names = list(Series = c("Lower", "Upper"))) ## scale_x_yearmon with custom discrete breaks df <- data.frame(dates = as.yearmon("2018-08") + 0:6/12, values = c(2:6, 0, 1)) ggdf <- ggplot(df, aes(x = dates, y = values)) + geom_bar(position = "dodge", stat = "identity") + theme_light() + xlab("Month") + ylab("Values") ggdf ## with default scale_x_yearmon ggdf + scale_x_yearmon(breaks = df$dates) ## with custom discrete breaks } } zoo/man/na.locf.Rd0000644000175100001440000001331513303351064013462 0ustar hornikusers\name{na.locf} \alias{na.locf} \alias{na.locf0} \alias{na.locf.data.frame} \alias{na.locf.list} \alias{na.locf.default} \title{Last Observation Carried Forward} \description{ Generic function for replacing each \code{NA} with the most recent non-\code{NA} prior to it. } \usage{ na.locf(object, na.rm = TRUE, \dots) \method{na.locf}{default}(object, na.rm = TRUE, fromLast, rev, maxgap = Inf, rule = 2, \dots) na.locf0(object, fromLast = FALSE, maxgap = Inf, coredata = NULL) } \arguments{ \item{object}{an object.} \item{na.rm}{logical. Should leading \code{NA}s be removed?} \item{fromLast}{logical. Causes observations to be carried backward rather than forward. Default is \code{FALSE}. With a value of \code{TRUE} this corresponds to NOCB (next observation carried backward). It is not supported if \code{x} or \code{xout} is specified.} \item{rev}{Use \code{fromLast} instead. This argument will be eliminated in the future in favor of \code{fromLast}.} \item{maxgap}{Runs of more than \code{maxgap} \code{NA}s are retained, other \code{NA}s are removed and the last occurrence in the resulting series prior to each time point in \code{xout} is used as that time point's output value. (If \code{xout} is not specified this reduces to retaining runs of more than \code{maxgap} \code{NA}s while filling other \code{NA}s with the last occurrence of a non-\code{NA}.)} \item{rule}{See \code{\link{approx}}.} \item{\dots}{further arguments passed to methods.} \item{coredata}{logical. Should LOCF be applied to the core data of a (time series) object and then assigned to the original object again? By default, this strategy is applied to time series classes (e.g., \code{ts}, \code{zoo}, \code{xts}, etc.) where it preserves the time index.} } \value{ An object in which each \code{NA} in the input object is replaced by the most recent non-\code{NA} prior to it. If there are no earlier non-\code{NA}s then the \code{NA} is omitted (if \code{na.rm = TRUE}) or it is not replaced (if \code{na.rm = FALSE}). The arguments \code{x} and \code{xout} can be used in which case they have the same meaning as in \code{\link{approx}}. Note that if a multi-column zoo object has a column entirely composed of \code{NA} then with \code{na.rm = TRUE}, the default, the above implies that the resulting object will have zero rows. Use \code{na.rm = FALSE} to preserve the \code{NA} values instead. The function \code{na.locf0} is the workhorse function underlying the default \code{na.locf} method. It has more limited capabilities but is faster for the special cases it covers. Implicitly, it uses \code{na.rm=FALSE}. } \seealso{\code{\link{zoo}}} \examples{ az <- zoo(1:6) bz <- zoo(c(2,NA,1,4,5,2)) na.locf(bz) na.locf(bz, fromLast = TRUE) cz <- zoo(c(NA,9,3,2,3,2)) na.locf(cz) # generate and fill in missing dates z <- zoo(c(0.007306621, 0.007659046, 0.007681013, 0.007817548, 0.007847579, 0.007867313), as.Date(c("1993-01-01", "1993-01-09", "1993-01-16", "1993-01-23", "1993-01-30", "1993-02-06"))) g <- seq(start(z), end(z), "day") na.locf(z, xout = g) # similar but use a 2 second grid z <- zoo(1:9, as.POSIXct(c("2010-01-04 09:30:02", "2010-01-04 09:30:06", "2010-01-04 09:30:07", "2010-01-04 09:30:08", "2010-01-04 09:30:09", "2010-01-04 09:30:10", "2010-01-04 09:30:11", "2010-01-04 09:30:13", "2010-01-04 09:30:14"))) g <- seq(start(z), end(z), by = "2 sec") na.locf(z, xout = g) ## get 5th of every month or most recent date prior to 5th if 5th missing. ## Result has index of the date actually used. z <- zoo(c(1311.56, 1309.04, 1295.5, 1296.6, 1286.57, 1288.12, 1289.12, 1289.12, 1285.33, 1307.65, 1309.93, 1311.46, 1311.28, 1308.11, 1301.74, 1305.41, 1309.72, 1310.61, 1305.19, 1313.21, 1307.85, 1312.25, 1325.76), as.Date(c(13242, 13244, 13245, 13248, 13249, 13250, 13251, 13252, 13255, 13256, 13257, 13258, 13259, 13262, 13263, 13264, 13265, 13266, 13269, 13270, 13271, 13272, 13274))) # z.na is same as z but with missing days added (with NAs) # It is formed by merging z with a zero with series having all the dates. rng <- range(time(z)) z.na <- merge(z, zoo(, seq(rng[1], rng[2], by = "day"))) # use na.locf to bring values forward picking off 5th of month na.locf(z.na)[as.POSIXlt(time(z.na))$mday == 5] ## this is the same as the last one except instead of always using the ## 5th of month in the result we show the date actually used # idx has NAs wherever z.na does but has 1, 2, 3, ... instead of # z.na's data values (so idx can be used for indexing) idx <- coredata(na.locf(seq_along(z.na) + (0 * z.na))) # pick off those elements of z.na that correspond to 5th z.na[idx[as.POSIXlt(time(z.na))$mday == 5]] ## only fill single-day gaps merge(z.na, filled1 = na.locf(z.na, maxgap = 1)) ## fill NAs in first column by inflating the most recent non-NA ## by the growth in second column. Note that elements of x-x ## are NA if the corresponding element of x is NA and zero else m <- zoo(cbind(c(1, 2, NA, NA, 5, NA, NA), seq(7)^2), as.Date(1:7)) r <- na.locf(m[,1]) * m[,2] / na.locf(m[,2] + (m[,1]-m[,1])) cbind(V1 = r, V2 = m[,2]) ## repeat a quarterly value every month ## preserving NAs zq <- zoo(c(1, NA, 3, 4), as.yearqtr(2000) + 0:3/4) tt <- as.yearmon(start(zq)) + seq(0, len = 3 * length(zq))/12 na.locf(zq, xout = tt, maxgap = 0) ## na.locf() can also be mimicked with ave() x <- c(NA, 10, NA, NA, 20, NA) f <- function(x) x[1] ave(x, cumsum(!is.na(x)), FUN = f) ## by replacing f() with other functions various generalizations can be ## obtained, e.g., f <- function(x) if (length(x) > 3) x else x[1] # like maxgap f <- function(x) replace(x, 1:min(length(x)), 3) # replace up to 2 NAs f <- function(x) if (!is.na(x[1]) && x[1] > 0) x[1] else x # only positve numbers } \keyword{ts} zoo/man/merge.zoo.Rd0000644000175100001440000001471014300522266014051 0ustar hornikusers\name{merge.zoo} \alias{merge.zoo} \alias{rbind.zoo} \alias{c.zoo} \alias{cbind.zoo} \title{Merge Two or More zoo Objects} \description{ Merge two zoo objects by common indexes (times), or do other versions of database \emph{join} operations. } \usage{ \method{merge}{zoo}(\dots, all = TRUE, fill = NA, suffixes = NULL, check.names = FALSE, retclass = c("zoo", "list", "data.frame"), drop = TRUE, sep = ".") } \arguments{ \item{\dots}{two or more objects, usually of class \code{"zoo"}.} \item{all}{logical vector having the same length as the number of \code{"zoo"} objects to be merged (otherwise expanded).} \item{fill}{an element for filling gaps in merged \code{"zoo"} objects (if any).} \item{suffixes}{character vector of the same length as the number of \code{"zoo"} objects specifying the suffixes to be used for making the merged column names unique.} \item{check.names}{See \code{link{read.table}}.} \item{retclass}{character that specifies the class of the returned result. It can be \code{"zoo"} (the default), \code{"list"} or \code{NULL}. For details see below.} \item{drop}{logical. If a \code{"zoo"} object without observations is merged with a one-dimensional \code{"zoo"} object (vector or 1-column matrix), should the result be a vector (\code{drop = TRUE}) or a 1-column matrix (\code{drop = FALSE})? The former is the default in the \code{Merge} method, the latter in the \code{cbind} method.} \item{sep}{character. Separator character that should be used when pasting \code{suffixes} to column names for making them unique.} } \details{ The \code{merge} method for \code{"zoo"} objects combines the columns of several objects along the union of the dates for \code{all = TRUE}, the default, or the intersection of their dates for \code{all = FALSE} filling up the created gaps (if any) with the \code{fill} pattern. The first argument must be a \code{zoo} object. If any of the remaining arguments are plain vectors or matrices with the same length or number of rows as the first argument then such arguments are coerced to \code{"zoo"} using \code{as.zoo}. If they are plain but have length 1 then they are merged after all non-scalars such that their column is filled with the value of the scalar. \code{all} can be a vector of the same length as the number of \code{"zoo"} objects to merged (if not, it is expanded): All indexes (times) of the objects corresponding to \code{TRUE} are included, for those corresponding to \code{FALSE} only the indexes present in all objects are included. This allows intersection, union and left and right joins to be expressed. If \code{retclass} is \code{"zoo"} (the default) a single merged \code{"zoo"} object is returned. If it is set to \code{"list"} a list of \code{"zoo"} objects is returned. If \code{retclass = NULL} then instead of returning a value it updates each argument (if it is a variable rather than an expression) in place so as to extend or reduce it to use the common index vector. The indexes of different \code{"zoo"} objects can be of different classes and are coerced to one class in the resulting object (with a warning). The default \code{cbind} method is essentially the default \code{merge} method, but does not support the \code{retclass} argument. The \code{rbind} method combines the dates of the \code{"zoo"} objects (duplicate dates are not allowed) and combines the rows of the objects. Furthermore, the \code{c} method is identical to the \code{rbind} method. } \value{ An object of class \code{"zoo"} if \code{retclass="zoo"}, an object of class \code{"list"} if \code{retclass="list"} or modified arguments as explained above if \code{retclass=NULL}. If the result is an object of class \code{"zoo"} then its frequency is the common frequency of its zoo arguments, if they have a common frequency. } \seealso{\code{\link{zoo}}} \examples{ ## simple merging x.date <- as.Date(paste(2003, 02, c(1, 3, 7, 9, 14), sep = "-")) x <- zoo(rnorm(5), x.date) y1 <- zoo(matrix(1:10, ncol = 2), 1:5) y2 <- zoo(matrix(rnorm(10), ncol = 2), 3:7) ## using arguments `fill' and `suffixes' merge(y1, y2, all = FALSE) merge(y1, y2, all = FALSE, suffixes = c("a", "b")) merge(y1, y2, all = TRUE) merge(y1, y2, all = TRUE, fill = 0) ## if different index classes are merged, as in ## the next merge example then ## a warning is issued and ### the indexes are coerced. ## It is up to the user to ensure that the result makes sense. merge(x, y1, y2, all = TRUE) ## extend an irregular series to a regular one: # create a constant series z <- zoo(1, seq(4)[-2]) # create a 0 dimensional zoo series z0 <- zoo(, 1:4) # do the extension merge(z, z0) # same but with zero fill merge(z, z0, fill = 0) merge(z, coredata(z), 1) ## merge multiple series represented in a long form data frame ## into a multivariate zoo series and plot, one series for each site. ## Additional examples can be found here: ## https://stat.ethz.ch/pipermail/r-help/2009-February/187094.html ## https://stat.ethz.ch/pipermail/r-help/2009-February/187096.html ## m <- 5 # no of years n <- 6 # no of sites sites <- LETTERS[1:n] suppressWarnings(RNGversion("3.5.0")) set.seed(1) DF <- data.frame(site = sites, year = 2000 + 1:m, data = rnorm(m*n)) tozoo <- function(x) zoo(x$data, x$year) Data <- do.call(merge, lapply(split(DF, DF$site), tozoo)) plot(Data, screen = 1, col = 1:n, pch = 1:n, type = "o", xlab = "") legend("bottomleft", legend = sites, lty = 1, pch = 1:n, col = 1:n) ## for each index value in x merge it with the closest index value in y ## but retaining x's times. x<-zoo(1:3,as.Date(c("1992-12-13", "1997-05-12", "1997-07-13"))) y<-zoo(1:5,as.Date(c("1992-12-15", "1992-12-16", "1997-05-10","1997-05-19", "1997-07-13"))) f <- function(u) which.min(abs(as.numeric(index(y)) - as.numeric(u))) ix <- sapply(index(x), f) cbind(x, y = coredata(y)[ix]) ## this merges each element of x with the closest time point in y at or ## after x's time point (whereas in previous example it could be before ## or after) window(na.locf(merge(x, y), fromLast = TRUE), index(x)) ## c() can combine several zoo series, e.g., zoo series with Date index z <- zoo(1:5, as.Date("2000-01-01") + 0:4) z2 <- zoo(6:7, time(z)[length(z)] + 1:2) ## c() combines these in a single series c(z, z2) ## the order does not matter c(z2, z) ## note, however, that combining a zoo series with an unclassed vector ## of observations would try to coerce the indexes first ## which might either give an unexpected result or an error in R >= 4.1.0 ## c(z, 6:7) } \keyword{ts} zoo/man/na.approx.Rd0000644000175100001440000001353413563216250014060 0ustar hornikusers\name{na.approx} \alias{na.approx} \alias{na.approx.zoo} \alias{na.approx.zooreg} \alias{na.approx.ts} \alias{na.approx.default} \alias{na.spline} \alias{na.spline.zoo} \alias{na.spline.zooreg} \alias{na.spline.ts} \alias{na.spline.default} \title{Replace NA by Interpolation} \description{ Generic functions for replacing each \code{NA} with interpolated values. } \usage{ na.approx(object, \dots) \method{na.approx}{zoo}(object, x = index(object), xout, \dots, na.rm = TRUE, maxgap = Inf, along) \method{na.approx}{zooreg}(object, \dots) \method{na.approx}{ts}(object, \dots) \method{na.approx}{default}(object, x = index(object), xout, \dots, na.rm = TRUE, maxgap = Inf, along) na.spline(object, \dots) \method{na.spline}{zoo}(object, x = index(object), xout, \dots, na.rm = TRUE, maxgap = Inf, along) \method{na.spline}{zooreg}(object, \dots) \method{na.spline}{ts}(object, \dots) \method{na.spline}{default}(object, x = index(object), xout, \dots, na.rm = TRUE, maxgap = Inf, along) } \arguments{ \item{object}{object in which \code{NA}s are to be replaced} \item{x, xout}{Variables to be used for interpolation as in \code{\link{approx}}.} \item{na.rm}{logical. If the result of the (spline) interpolation still results in leading and/or trailing \code{NA}s, should these be removed (using \code{\link{na.trim}})?} \item{maxgap}{maximum number of consecutive \code{NA}s to fill. Any longer gaps will be left unchanged. Note that all methods listed above can accept \code{maxgap} as it is ultimately passed to the \code{default} method. In \code{na.spline} the \code{maxgap} argument cannot be combined with \code{xout}, though.} \item{along}{deprecated.} \item{\dots}{further arguments passed to methods. The \code{n} argument of \code{\link{approx}} is currently not supported.} } \details{ Missing values (\code{NA}s) are replaced by linear interpolation via \code{\link{approx}} or cubic spline interpolation via \code{\link{spline}}, respectively. It can also be used for series disaggregation by specifying \code{xout}. By default the index associated with \code{object} is used for interpolation. Note, that if this calls \code{index.default} this gives an equidistant spacing \code{1:NROW(object)}. If \code{object} is a matrix or data.frame, the interpolation is done separately for each column. If \code{obj} is a plain vector then \code{na.approx(obj, x, y, xout, ...)} returns \code{approx(x = x[!na], y = coredata(obj)[!na], xout = xout, ...)} (where \code{na} indicates observations with \code{NA}) such that \code{xout} defaults to \code{x}. Note that if there are less than two non-\code{NA}s then \code{approx()} cannot be applied and thus no \code{NA}s can be replaced. If \code{obj} is a \code{zoo}, \code{zooreg} or \code{ts} object its \code{coredata} value is processed as described and its time index is \code{xout} if specified and \code{index(obj)} otherwise. If \code{obj} is two dimensional then the above is applied to each column separately. For examples, see below. If \code{obj} has more than one column, the above strategy is applied to each column. } \value{ An object of similar structure as \code{object} with \code{NA}s replaced by interpolation. For \code{na.approx} only the internal \code{NA}s are replaced and leading or trailing \code{NA}s are omitted if \code{na.rm = TRUE} or not replaced if \code{na.rm = FALSE}. } \seealso{\code{\link{zoo}}, \code{\link{approx}}, \code{\link{na.contiguous}}, \code{\link{na.locf}}, \code{\link{na.omit}}, \code{\link{na.trim}}, \code{\link{spline}}, \code{\link[stinepack]{stinterp}} } \examples{ z <- zoo(c(2, NA, 1, 4, 5, 2), c(1, 3, 4, 6, 7, 8)) ## use underlying time scale for interpolation na.approx(z) ## use equidistant spacing na.approx(z, 1:6) # with and without na.rm = FALSE zz <- c(NA, 9, 3, NA, 3, 2) na.approx(zz, na.rm = FALSE) na.approx(zz) d0 <- as.Date("2000-01-01") z <- zoo(c(11, NA, 13, NA, 15, NA), d0 + 1:6) # NA fill, drop or keep leading/trailing NAs na.approx(z) na.approx(z, na.rm = FALSE) # extrapolate to point outside of range of time points # (a) drop NA, (b) keep NA, (c) extrapolate using rule = 2 from approx() na.approx(z, xout = d0 + 7) na.approx(z, xout = d0 + 7, na.rm = FALSE) na.approx(z, xout = d0 + 7, rule = 2) # use splines - extrapolation handled differently z <- zoo(c(11, NA, 13, NA, 15, NA), d0 + 1:6) na.spline(z) na.spline(z, na.rm = FALSE) na.spline(z, xout = d0 + 1:6) na.spline(z, xout = d0 + 2:5) na.spline(z, xout = d0 + 7) na.spline(z, xout = d0 + 7, na.rm = FALSE) ## using na.approx for disaggregation zy <- zoo(1:3, 2000:2001) # yearly to monthly series zmo <- na.approx(zy, xout = as.yearmon(2000+0:13/12)) zmo # monthly to daily series sq <- seq(as.Date(start(zmo)), as.Date(end(zmo), frac = 1), by = "day") zd <- na.approx(zmo, x = as.Date, xout = sq) head(zd) # weekly to daily series zww <- zoo(1:3, as.Date("2001-01-01") + seq(0, length = 3, by = 7)) zww zdd <- na.approx(zww, xout = seq(start(zww), end(zww), by = "day")) zdd # The lines do not show up because of the NAs plot(cbind(z, z), type = "b", screen = 1) # use na.approx to force lines to appear plot(cbind(z, na.approx(z)), type = "b", screen = 1) # Workaround where less than 2 NAs can appear in a column za <- zoo(cbind(1:5, NA, c(1:3, NA, 5), NA)); za ix <- colSums(!is.na(za)) > 0 za[, ix] <- na.approx(za[, ix]); za # using na.approx to create regularly spaced series # z has points at 10, 20 and 40 minutes while output also has a point at 30 if(require("chron")) { tt <- as.chron("2000-01-01 10:00:00") + c(1, 2, 4) * as.numeric(times("00:10:00")) z <- zoo(1:3, tt) tseq <- seq(start(z), end(z), by = times("00:10:00")) na.approx(z, xout = tseq) } } \keyword{ts} zoo/man/make.par.list.Rd0000644000175100001440000000356611611315753014626 0ustar hornikusers\name{make.par.list} \alias{make.par.list} \title{Make a List from a Parameter Specification} \description{ Process parameters so that a list of parameter specifications is returned (used by \code{plot.zoo} and \code{xyplot.zoo}). } \usage{ make.par.list(nams, x, n, m, def, recycle = sum(unnamed) > 0) } \arguments{ \item{nams}{character vector with names of variables.} \item{x}{list or vector of parameter specifications, see details.} \item{n}{numeric, number of rows.} \item{m}{numeric, number of columns. (Only determines whether \code{m} is 1 or greater than 1.} \item{def}{default parameter value.} \item{recycle}{logical. If \code{TRUE} recycle columns to provide unspecified ones. If \code{FALSE} use \code{def} to provide unspecified ones. This only applies to entire columns. Within columns recycling is always done regardless of how \code{recycle} is set. Defaults to \code{TRUE} if there is at least one unnamed variable and defaults to \code{FALSE} if there are only named variables in \code{x}.} } \details{ This function is currently intended for internal use. It is currently used by \code{plot.zoo} and \code{xyplot.zoo} but might also be used in the future to create additional new plotting routines. It creates a new list which uses the named variables from \code{x} and then assigns the unnamed in order. For the remaining variables assign them the default value if \code{!recycle} or recycle the unnamed variables if \code{recycle}. } \value{ A list of parameters, see details. } \examples{ make.par.list(letters[1:5], 1:5, 3, 5) suppressWarnings( make.par.list(letters[1:5], 1:4, 3, 5, 99) ) make.par.list(letters[1:5], c(d=3), 3, 5, 99) make.par.list(letters[1:5], list(d=1:2, 99), 3, 5) make.par.list(letters[1:5], list(d=1:2, 99, 100), 3, 5) } \keyword{ts} zoo/man/xyplot.zoo.Rd0000644000175100001440000002307713667730774014343 0ustar hornikusers\name{xyplot.zoo} \alias{xyplot.zoo} \alias{xyplot.its} \alias{xyplot.tis} \alias{llines.zoo} \alias{llines.its} \alias{llines.tis} \alias{lpoints.zoo} \alias{lpoints.its} \alias{lpoints.tis} \alias{ltext.zoo} \alias{ltext.its} \alias{ltext.tis} %% Deprecated: \alias{panel.lines.zoo} \alias{panel.lines.ts} \alias{panel.lines.its} \alias{panel.lines.tis} \alias{panel.points.zoo} \alias{panel.points.ts} \alias{panel.points.its} \alias{panel.points.tis} \alias{panel.text.zoo} \alias{panel.text.ts} \alias{panel.text.its} \alias{panel.text.tis} \alias{panel.plot.default} \alias{panel.plot.custom} %% Unnecessary?: \alias{panel.segments.zoo} \alias{panel.segments.ts} \alias{panel.segments.its} \alias{panel.segments.tis} \alias{panel.rect.zoo} \alias{panel.rect.ts} \alias{panel.rect.its} \alias{panel.rect.tis} \alias{panel.polygon.zoo} \alias{panel.polygon.ts} \alias{panel.polygon.its} \alias{panel.polygon.tis} \title{Plot zoo Series with Lattice} \description{ \code{xyplot} methods for time series objects (of class \code{"zoo"}, \code{"its"}, or \code{"tis"}). } \usage{ \method{xyplot}{zoo}(x, data, ...) \method{llines}{zoo}(x, y = NULL, ...) \method{lpoints}{zoo}(x, y = NULL, ...) \method{ltext}{zoo}(x, y = NULL, ...) panel.segments.zoo(x0, x1, ...) panel.rect.zoo(x0, x1, ...) panel.polygon.zoo(x, ...) } \arguments{ \item{x, x0, x1}{time series object of class \code{"zoo"}, \code{"its"} or \code{"tis"}. For \code{panel.plot.default} it should be a numeric vector.} \item{y}{numeric vector or matrix.} \item{data}{not used.} \item{\dots}{ arguments are passed to \code{\link[lattice]{xyplot.ts}}, and may be passed through to \code{\link[lattice]{xyplot}} and \code{\link[lattice]{panel.xyplot}}. Some of the commonly used arguments are: \describe{ \item{\code{screens}}{factor (or coerced to factor) whose levels specify which graph each series is to be plotted in. \code{screens = c(1, 2, 1)} would plot series 1, 2 and 3 in graphs 1, 2 and 1. This also defines the strip text in multi-panel plots.} \item{\code{scales}}{ the default is set so that all series have the \code{"same"} X axis but \code{"free"} Y axis. See \code{\link[lattice]{xyplot}} in the \pkg{lattice} package for more information on \code{scales}. } \item{\code{layout}}{numeric vector of length 2 specifying number of columns and rows in the plot, see \code{\link[lattice]{xyplot}} for more details. The default is to fill columns with up to 6 rows.} \item{\code{xlab}}{character string used as the X axis label.} \item{\code{ylab}}{character string used as the Y axis label. If there are multiple panels it may be a character vector the same length as the number of panels, but \emph{NOTE} in this case the vector should be reversed OR the argument \code{as.table} set to \code{FALSE}.} \item{\code{lty, lwd, pch, type, col}}{ graphical arguments passed to \code{\link[lattice]{panel.xyplot}}. These arguments can also be vectors or (named) lists, see details for more information.} } } } \details{ \code{xyplot.zoo} plots a \code{"zoo"}, \code{"its"} or \code{"tis"} object using \code{\link[lattice]{xyplot.ts}} from \pkg{lattice}. Series of other classes are coerced to \code{"zoo"} first. The handling of several graphical parameters is more flexible for multivariate series. These parameters can be vectors of the same length as the number of series plotted or are recycled if shorter. They can also be (partially) named list, e.g., \code{list(A = c(1,2), c(3,4))} in which \code{c(3, 4)} is the default value and \code{c(1, 2)} the value only for series \code{A}. The \code{screens} argument can be specified in a similar way. Note that since \pkg{zoo} 1.6-3 \code{plot.panel.default} and \code{plot.panel.custom} are no longer necessary, as normal panel functions (\code{\link[lattice]{panel.xyplot}} by default) will work. Similarly, there are now methods for the generic \pkg{lattice} drawing functions \code{\link[lattice]{llines}}, \code{\link[lattice:llines]{lpoints}}, and \code{\link[lattice:llines]{ltext}}. These can also be called as \code{panel.lines}, \code{panel.points}, and \code{panel.text}, respectively. The old interfaces (\code{panel.lines.zoo}, \code{panel.points.zoo}, and \code{panel.text.zoo}), will be removed in future versions. \code{panel.polygon.zoo} may also be removed. } \value{ Invisibly returns a \code{"trellis"} class object. Printing this object using \code{print} will display it. } \seealso{\code{\link[lattice]{xyplot.ts}}, \code{\link{zoo}}, \code{\link{plot.ts}}, \code{\link{barplot}}, \code{\link{plot.zoo}}} \examples{ if(require("lattice") & require("grid")) { suppressWarnings(RNGversion("3.5.0")) set.seed(1) z <- zoo(cbind(a = 1:5, b = 11:15, c = 21:25) + rnorm(5)) # plot z using same Y axis on all plots xyplot(z, scales = list(y = list(relation = "same", alternating = FALSE))) # plot a double-line-width running mean on the panel of b. # Also add a grid. # We show two ways to do it. # change strip background to levels of grey # If you like the defaults, this can be omitted. strip.background <- trellis.par.get("strip.background") trellis.par.set(strip.background = list(col = grey(7:1/8))) # Number 1. Using trellis.focus. print( xyplot(z) ) trellis.focus("panel", 1, 2, highlight = FALSE) # (or just trellis.focus() for interactive use) z.mean <- rollmean(z, 3) panel.lines(z.mean[,2], lwd = 2) panel.grid(h = 10, v = 10, col = "grey", lty = 3) trellis.unfocus() # Number 2. Using a custom panel routine. xyplot(z, panel = function(x, y, ...) { if (packet.number() == 2) { panel.grid(h = 10, v = 10, col = "grey", lty = 3) panel.lines(rollmean(zoo(y, x), 3), lwd = 2) } panel.xyplot(x, y, ...) }) # plot a light grey rectangle "behind" panel b trellis.focus("panel", 1, 2) grid.rect(x = 2, w = 1, default.units = "native", gp = gpar(fill = "light grey")) # do.call("panel.xyplot", trellis.panelArgs()) do.call("panel.lines", trellis.panelArgs()[1:2]) trellis.unfocus() # a better method is to use a custom panel function. # see also panel.xblocks() and layer() in the latticeExtra package. # same but make first panel twice as large as others lopt <- list(layout.heights = list(panel = list(x = c(2,1,1)))) xyplot(z, lattice.options = lopt) # add a grid update(trellis.last.object(), type = c("l", "g")) # Plot all in one panel. xyplot(z, screens = 1) # Same with default styles and auto.key: xyplot(z, superpose = TRUE) # Plot first two columns in first panel and third column in second panel. # Plot first series using points, second series using lines and third # series via overprinting both lines and points # Use colors 1, 2 and 3 for the three series (1=black, 2=red, 3=green) # Make 2nd (lower) panel 3x the height of the 1st (upper) panel # Also make the strip background orange. p <- xyplot(z, screens = c(1,1,2), type = c("p", "l", "o"), col = 1:3, par.settings = list(strip.background = list(col = "orange"))) print(p, panel.height = list(y = c(1, 3), units = "null")) # Example of using a custom axis # Months are labelled with smaller ticks for weeks and even smaller # ticks for days. Days <- seq(from = as.Date("2006-1-1"), to = as.Date("2006-8-8"), by = "day") z1 <- zoo(seq(length(Days))^2, Days) Months <- Days[format(Days, "\%d") == "01"] Weeks <- Days[format(Days, "\%w") == "0"] print( xyplot(z1, scales = list(x = list(at = Months))) ) trellis.focus("panel", 1, 1, clip.off = TRUE) panel.axis("bottom", check.overlap = TRUE, outside = TRUE, labels = FALSE, tck = .7, at = as.numeric(Weeks)) panel.axis("bottom", check.overlap = TRUE, outside = TRUE, labels = FALSE, tck = .4, at = as.numeric(Days)) trellis.unfocus() trellis.par.set(strip.background = strip.background) # separate the panels and suppress the ticks on very top xyplot(z, between = list(y = 1), scales = list(tck = c(1,0))) # left strips but no top strips xyplot(z, screens = colnames(z), strip = FALSE, strip.left = TRUE) # plot list of zoo objects using different x scales z.l <- list( zoo(cbind(a = rnorm(10), b = rnorm(10)), as.Date("2006-01-01") + 0:9), zoo(cbind(c = rnorm(10), d = rnorm(10)), as.Date("2006-12-01") + 0:9) ) zm <- do.call(merge, z.l) xlim <- lapply(zm, function(x) range(time(na.omit(x)))) xyplot(zm, xlim = xlim, scale = list(relation = "free")) # to avoid merging see xyplot.list() in the latticeExtra package. } \dontrun{ ## playwith (>= 0.9) library("playwith") z3 <- zoo(cbind(a = rnorm(100), b = rnorm(100) + 1), as.Date(1:100)) playwith(xyplot(z3), time.mode = TRUE) # hold down Shift key and drag to zoom in to a time period. # then use the horizontal scroll bar. # set custom labels; right click on points to view or add labels labs <- paste(round(z3,1), index(z3), sep = "@") trellis.par.set(user.text = list(cex = 0.7)) playwith(xyplot(z3, type = "o"), labels = labs) # this returns indexes into times of clicked points ids <- playGetIDs() z3[ids,] ## another example of using playwith with zoo # set up data dat <- zoo(matrix(rnorm(100*100),ncol=100), Sys.Date()+1:100) colnames(dat) <- paste("Series", 1:100) # This will give you a spin button to choose the column to plot, # and a button to print out the current series number. playwith(xyplot(dat[,c(1,i)]), parameters = list(i = 1:100, do_something = function(playState) print(playState$env$i)) } } \keyword{hplot} \keyword{ts} zoo/man/zooreg.Rd0000644000175100001440000001560113721601645013456 0ustar hornikusers\name{zooreg} \alias{zooreg} \alias{frequency.zooreg} \alias{frequency.zoo} \alias{deltat.zooreg} \alias{deltat.zoo} \alias{cycle.zooreg} \alias{cycle.zoo} \alias{as.zooreg} \alias{as.zooreg.default} \alias{as.zooreg.ts} \alias{as.zooreg.its} \alias{as.zooreg.xts} \alias{as.ts.zooreg} \alias{as.zoo.zooreg} \alias{as.zooreg.zoo} \alias{index<-.zooreg} \alias{time<-.zooreg} \alias{lag.zooreg} \title{Regular zoo Series} \description{ \code{zooreg} is the creator for the S3 class \code{"zooreg"} for regular \code{"zoo"} series. It inherits from \code{"zoo"} and is the analogue to \code{\link{ts}}. } \usage{ zooreg(data, start = 1, end = numeric(), frequency = 1, deltat = 1, ts.eps = getOption("ts.eps"), order.by = NULL, calendar = getOption("zoo.calendar", TRUE)) } \arguments{ \item{data}{a numeric vector, matrix or a factor.} \item{start}{the time of the first observation. Either a single number or a vector of two integers, which specify a natural time unit and a (1-based) number of samples into the time unit.} \item{end}{the time of the last observation, specified in the same way as \code{start}.} \item{frequency}{the number of observations per unit of time.} \item{deltat}{the fraction of the sampling period between successive observations; e.g., 1/12 for monthly data. Only one of \code{frequency} or \code{deltat} should be provided.} \item{ts.eps}{time series comparison tolerance. Frequencies are considered equal if their absolute difference is less than \code{ts.eps}.} \item{order.by}{a vector by which the observations in \code{x} are ordered. If this is specified the arguments \code{start} and \code{end} are ignored and \code{zoo(data, order.by, frequency)} is called. See \code{\link{zoo}} for more information.} \item{calendar}{logical. Should \code{\link{yearqtr}} or \code{\link{yearmon}} be used for a numeric time index with frequency 4 or 12, respectively?} } \details{ Strictly regular series are those whose time points are equally spaced. Weakly regular series are strictly regular time series in which some of the points may have been removed but still have the original underlying frequency associated with them. \code{"zooreg"} is a subclass of \code{"zoo"} that is used to represent both weakly and strictly regular series. Internally, it is the same as \code{"zoo"} except it also has a \code{"frequency"} attribute. Its index class is more restricted than \code{"zoo"}. The index: 1. must be numeric or a class which can be coerced via \code{as.numeric} (such as \code{\link{yearmon}}, \code{\link{yearqtr}}, \code{\link{Date}}, \code{\link{POSIXct}}, \code{\link[tis]{tis}}, \code{\link[xts]{xts}}, etc.). 2. when converted to numeric must be expressible as multiples of 1/frequency. 3. group generic functions \code{\link{Ops}} should be defined, i.e., adding/subtracting a numeric to/from the index class should produce the correct value of the index class again. \code{zooreg} is the \code{zoo} analogue to \code{\link{ts}}. The arguments are almost identical, only in the case where \code{order.by} is specified, \code{\link{zoo}} is called with \code{zoo(data, order.by, frequency)}. It creates a regular series of class \code{"zooreg"} which inherits from \code{"zoo"}. It is essentially a \code{"zoo"} series with an additional \code{"frequency"} attribute. In the creation of \code{"zooreg"} objects (via \code{\link{zoo}}, \code{\link{zooreg}}, or coercion functions) it is always check whether the index specified complies with the frequency specified. The class \code{"zooreg"} offers two advantages over code \code{"ts"}: 1. The index does not have to be plain numeric (although that is the default), it just must be coercible to numeric, thus printing and plotting can be customized. 2. This class can not only represent strictly regular series, but also series with an underlying regularity, i.e., where some observations from a regular grid are omitted. Hence, \code{"zooreg"} is a bridge between \code{"ts"} and \code{"zoo"} and can be employed to coerce back and forth between the two classes. The coercion function \code{as.zoo.ts} returns therefore an object of class \code{"zooreg"} inheriting from \code{"zoo"}. Coercion between \code{"zooreg"} and \code{"zoo"} is also available and drops or tries to add a frequency respectively. For checking whether a series is strictly regular or does have an underlying regularity the generic function \code{\link{is.regular}} can be used. Methods to standard generics for regular series such as \code{\link{frequency}}, \code{\link{deltat}} and \code{\link{cycle}} are available for both \code{"zooreg"} and \code{"zoo"} objects. In the latter case, it is checked first (in a data-driven way) whether the series is in fact regular or not. \code{as.zooreg.tis} has a \code{class} argument whose value represents the class of the index of the \code{zooreg} object into which the \code{tis} object is converted. The default value is \code{"ti"}. Note that the frequency of the \code{zooreg} object will not necessarily be the same as the frequency of the \code{tis} object that it is converted from. } \value{ An object of class \code{"zooreg"} which inherits from \code{"zoo"}. It is essentially a \code{"zoo"} series with a \code{"frequency"} attribute. } \seealso{\code{\link{zoo}}, \code{\link{is.regular}}} \examples{ ## equivalent specifications of a quarterly series ## starting in the second quarter of 1959. zooreg(1:10, frequency = 4, start = c(1959, 2)) as.zoo(ts(1:10, frequency = 4, start = c(1959, 2))) zoo(1:10, seq(1959.25, 1961.5, by = 0.25), frequency = 4) ## use yearqtr class for indexing the same series z <- zoo(1:10, yearqtr(seq(1959.25, 1961.5, by = 0.25)), frequency = 4) z z[-(3:4)] ## create a regular series with a "Date" index zooreg(1:5, start = as.Date("2000-01-01")) ## or with "yearmon" index zooreg(1:5, end = yearmon(2000)) ## lag and diff (as diff is defined in terms of lag) ## act differently on zoo and zooreg objects! ## lag.zoo moves a point to the adjacent time whereas ## lag.zooreg moves a point by deltat x <- c(1, 2, 3, 6) zz <- zoo(x, x) zr <- as.zooreg(zz) lag(zz, k = -1) lag(zr, k = -1) diff(zz) diff(zr) ## lag.zooreg wihtout and with na.pad lag(zr, k = -1) lag(zr, k = -1, na.pad = TRUE) ## standard methods available for regular series frequency(z) deltat(z) cycle(z) cycle(z[-(3:4)]) zz <- zoo(1:6, as.Date(c("1960-01-29", "1960-02-29", "1960-03-31", "1960-04-29", "1960-05-31", "1960-06-30"))) # this converts zz to "zooreg" and then to "ts" expanding it to a daily # series which is 154 elements long, most with NAs. \dontrun{ length(as.ts(zz)) # 154 } # probably a monthly "ts" series rather than a daily one was wanted. # This variation of the last line gives a result only 6 elements long. length(as.ts(aggregate(zz, as.yearmon, c))) # 6 zzr <- as.zooreg(zz) dd <- as.Date(c("2000-01-01", "2000-02-01", "2000-03-01", "2000-04-01")) zrd <- as.zooreg(zoo(1:4, dd)) } \keyword{ts} zoo/man/read.zoo.Rd0000644000175100001440000003214613573302045013672 0ustar hornikusers\name{read.zoo} \alias{read.zoo} \alias{read.table.zoo} \alias{read.csv.zoo} \alias{read.csv2.zoo} \alias{read.delim.zoo} \alias{read.delim2.zoo} \alias{write.zoo} \title{Reading and Writing zoo Series} \description{ \code{read.zoo} and \code{write.zoo} are convenience functions for reading and writing \code{"zoo"} series from/to text files. They are convenience interfaces to \code{read.table} and \code{write.table}, respectively. To employ \code{read.csv}, \code{read.csv2}, \code{read.delim}, \code{read.delim2} instead of \code{read.table} additional functions \code{read.csv.zoo} etc. are provided. } \usage{ read.zoo(file, format = "", tz = "", FUN = NULL, regular = FALSE, index.column = 1, drop = TRUE, FUN2 = NULL, split = NULL, aggregate = FALSE, \dots, text, read = read.table) write.zoo(x, file = "", index.name = "Index", row.names = FALSE, col.names = NULL, \dots) read.csv.zoo(\dots, read = read.csv) read.csv2.zoo(\dots, read = read.csv2) read.delim.zoo(\dots, read = read.delim) read.delim2.zoo(\dots, read = read.delim2) } \arguments{ \item{file}{character string or strings giving the name of the file(s) which the data are to be read from/written to. See \code{\link{read.table}} and \code{\link{write.table}} for more information. Alternatively, in \code{read.zoo}, \code{file} can be a \code{connection} or a \code{data.frame} (e.g., resulting from a previous \code{read.table} call) that is subsequently processed to a \code{"zoo"} series.} \item{format}{date format argument passed to \code{FUN}.} \item{tz}{time zone argument passed to \code{\link{as.POSIXct}}.} \item{FUN}{a function for computing the index from the first column of the data. See details.} \item{regular}{logical. Should the series be coerced to class \code{"zooreg"} (if the series is regular)?} \item{index.column}{numeric vector or list. The column names or numbers of the data frame in which the index/time is stored. If the \code{read.table} argument \code{colClasses} is used and \code{"NULL"} is among its components then \code{index.column} refers to the column numbers after the columns corresponding to \code{"NULL"} in \code{colClasses} have been removed. If specified as a list then one argument will be passed to argument \code{FUN} per component so that, for example, \code{index.column = list(1, 2)} will cause \code{FUN(x[,1], x[,2], \dots)} to be called whereas \code{index.column = list(1:2)} will cause \code{FUN(x[,1:2], \dots)} to be called where \code{x} is a data frame of characters data. Here \code{\dots} refers to \code{format} and/or \code{tz}, if they specified as arguments. \code{index.column = 0} can be used to specify that the row names be used as the index. In the case that no row names were input sequential numbering is used. If \code{index.column} is specified as an ordinary vector then if it has the same length as the number of arguments of \code{FUN} (or \code{FUN2} in the event that \code{FUN2} is specified and \code{FUN} is not) then \code{index.column} is converted to a list. Also it is always converted to a list if it has length 1.} \item{drop}{logical. If the data frame contains just a single data column, should the second dimension be dropped?} \item{x}{a \code{"zoo"} object.} \item{index.name}{character with name of the index column in the written data file.} \item{row.names}{logical. Should row names be written? Default is \code{FALSE} because the row names are just character representations of the index.} \item{col.names}{logical. Should column names be written? Default is to write column names only if \code{x} has column names.} \item{FUN2}{function. It is applied to the time index after \code{FUN} and before \code{aggregate}. If \code{FUN} is not specified but \code{FUN2} is specified then only \code{FUN2} is applied.} \item{split}{NULL or column number or name or vector of numbers or names. If not NULL then the data is assumed to be in long format and is split according to the indicated columns. See the \R \code{\link[stats]{reshape}} command for description of long data. If \code{split = Inf} then the first of each run among the times are made into a separate series, the second of each run and so on. If \code{split= -Inf} then the last of each run is made into a separate series, the second last and so on.} \item{aggregate}{logical or function. If set to \code{TRUE}, then \code{\link{aggregate.zoo}} is applied to the zoo object created to compute the \code{\link{mean}} of all values with the same time index. Alternatively, \code{aggregate} can be set to any other function that should be used for aggregation. If \code{FALSE} (the default), no aggregation is performed and a warning is given if there are any duplicated time indexes. Note that most \code{zoo} functions do not accept objects with duplicate time indexes. See \code{\link{aggregate.zoo}}.} \item{\dots}{further arguments passed to other functions. In the \code{read.*.zoo} the arguments are passed to the function specified in \code{read} (unless \code{file} is a \code{data.frame} already). In \code{write.zoo} the arguments are passed to \code{\link{write.table}}.} \item{text}{character. If \code{file} is not supplied and this is, then data are read from the value of \code{text} via a text connection. See below for an example.} \item{read}{function. The function for reading \code{file} (unless it is a \code{data.frame} already).} } \details{ \code{read.zoo} is a convenience function which should make it easier to read data from a text file and turn it into a \code{"zoo"} series immediately. \code{read.zoo} reads the data file via \code{read.table(file, \dots)}. The column \code{index.column} (by default the first) of the resulting data is interpreted to be the index/time, the remaining columns the corresponding data. (If the file only has only column then that is assumed to be the data column and \code{1, 2, \dots} are used for the index.) To assign the appropriate class to the index, \code{FUN} can be specified and is applied to the first column. To process the index, \code{read.zoo} calls \code{FUN} with the index as the first argument. If \code{FUN} is not specified, the following default is employed: (a) If \code{file} is a data frame with a single index column that appears to be a time index already, then \code{FUN = identity} is used. The conditions for a readily produced time index are: It is not \code{character} or \code{factor} (and the arguments \code{tz} and \code{format} must not be specified). (b) If the conditions from (a) do not hold then the following strategy is used. If there are multiple index columns they are pasted together with a space between each. Using the (pasted) index column: (1) If \code{tz} is specified then the index column is converted to \code{POSIXct}. (2) If \code{format} is specified then the index column is converted to \code{Date}. (3) Otherwise, a heuristic attempts to decide between \code{"numeric"}, \code{"POSIXct"}, and \code{"Date"} by trying them in that order (which may not always succeed though). By default, only the standard date/time format is used. Hence, supplying \code{format} and/or \code{tz} is necessary if some date/time format is used that is not the default. And even if the default format is appropriate for the index, explicitly supplying \code{FUN} or at least \code{format} and/or \code{tz} typically leads to more reliable results than the heuristic. If \code{regular} is set to \code{TRUE} and the resulting series has an underlying regularity, it is coerced to a \code{"zooreg"} series. To employ other functions than \code{read.table} to read the initial data, further convenience interfaces \code{read.csv.zoo} etc. are provided. \code{write.zoo} is a convenience function for writing \code{"zoo"} series to text files. It first coerces its argument to a \code{"data.frame"}, adds a column with the index and then calls \code{\link{write.table}}. See also \code{vignette("zoo-read", package = "zoo")} for detailed examples. } \value{ \code{read.zoo} returns an object of class \code{"zoo"} (or \code{"zooreg"}). } \note{\code{read.zoo} works by first reading the data in using \code{read.table} and then processing it. This implies that if the index field is entirely numeric the default is to pass it to \code{FUN} or the built-in date conversion routine a number, rather than a character string. Thus, a date field such as \code{09122007} intended to represent December 12, 2007 would be seen as \code{9122007} and interpreted as the 91st day thereby generating an error. This comment also applies to trailing decimals so that if \code{2000.10} were intended to represent the 10th month of 2000 in fact it would receive \code{2000.1} and regard it as the first month of 2000 unless similar precautions were taken. In the above cases the index field should be specified to be \code{"character"} so that leading or trailing zeros are not dropped. This can be done by specifying a \code{"character"} index column in the \code{"colClasses"} argument, which is passed to \code{read.table}, as shown in the examples below. } \seealso{\code{\link{zoo}}} \examples{ ## this manual page provides a few typical examples, many more cases ## are covered in vignette("zoo-read", package = "zoo") ## read text lines with a single date column Lines <- "2013-12-24 2 2013-12-25 3 2013-12-26 8" read.zoo(text = Lines, FUN = as.Date) # explicit coercion read.zoo(text = Lines, format = "\%Y-\%m-\%d") # same read.zoo(text = Lines) # same, via heuristic ## read text lines with date/time in separate columns Lines <- "2013-11-24 12:41:21 2 2013-12-25 12:41:22.25 3 2013-12-26 12:41:22.75 8" read.zoo(text = Lines, index = 1:2, FUN = paste, FUN2 = as.POSIXct) # explicit coercion read.zoo(text = Lines, index = 1:2, tz = "") # same read.zoo(text = Lines, index = 1:2) # same, via heuristic ## read text lines with month/year in separate columns Lines <- "Jan 1998 4.36 Feb 1998 4.34" read.zoo(text = Lines, index = 1:2, FUN = paste, FUN2 = as.yearmon) ## read directly from a data.frame (artificial and built-in BOD) dat <- data.frame(date = paste("2000-01-", 10:15, sep = ""), a = sin(1:6), b = cos(1:6)) read.zoo(dat) data("BOD", package = "datasets") read.zoo(BOD) \dontrun{ ## descriptions of typical examples ## turn *numeric* first column into yearmon index ## where number is year + fraction of year represented by month z <- read.zoo("foo.csv", sep = ",", FUN = as.yearmon) ## first column is of form yyyy.mm ## (Here we use format in place of as.character so that final zero ## is not dropped in dates like 2001.10 which as.character would do.) f <- function(x) as.yearmon(format(x, nsmall = 2), "\%Y.\%m") z <- read.zoo("foo.csv", header = TRUE, FUN = f) ## turn *character* first column into "Date" index ## Assume lines look like: 12/22/2007 1 2 z <- read.zoo("foo.tab", format = "\%m/\%d/\%Y") # Suppose lines look like: 09112007 1 2 and there is no header z <- read.zoo("foo.txt", format = "\%d\%m\%Y") ## csv file with first column of form YYYY-mm-dd HH:MM:SS ## Read in times as "chron" class. Requires chron 2.3-22 or later. z <- read.zoo("foo.csv", header = TRUE, sep = ",", FUN = as.chron) ## same but with custom format. Note as.chron uses POSIXt-style % formats ## Read in times as "chron" class. Requires chron 2.3-24 or later. z <- read.zoo("foo.csv", header = TRUE, sep = ",", FUN = as.chron, format = "%Y%m%d") ## same file format but read it in times as "POSIXct" class. z <- read.zoo("foo.csv", header = TRUE, sep = ",", tz = "") ## csv file with first column mm-dd-yyyy. Read times as "Date" class. z <- read.zoo("foo.csv", header = TRUE, sep = ",", format = "\%m-\%d-\%Y") ## whitespace separated file with first column of form YYYY-mm-ddTHH:MM:SS ## and no headers. T appears literally. Requires chron 2.3-22 or later. z <- read.zoo("foo.csv", FUN = as.chron) # read in all csv files in the current directory and merge them read.zoo(Sys.glob("*.csv"), header = TRUE, sep = ",") # We use "NULL" in colClasses for those columns we don't need but in # col.names we still have to include dummy names for them. Of what # is left the index is the first three columns (1:3) which we convert # to chron class times in FUN and then truncate to 5 seconds in FUN2. # Finally we use aggregate = mean to average over the 5 second intervals. library("chron") Lines <- "CVX 20070201 9 30 51 73.25 81400 0 CVX 20070201 9 30 51 73.25 100 0 CVX 20070201 9 30 51 73.25 100 0 CVX 20070201 9 30 51 73.25 300 0 CVX 20070201 9 30 51 73.25 81400 0 CVX 20070201 9 40 51 73.25 100 0 CVX 20070201 9 40 52 73.25 100 0 CVX 20070201 9 40 53 73.25 300 0" z <- read.zoo(text = Lines, colClasses = c("NULL", "NULL", "numeric", "numeric", "numeric", "numeric", "numeric", "NULL"), col.names = c("Symbol", "Date", "Hour", "Minute", "Second", "Price", "Volume", "junk"), index = 1:3, # do not count columns that are "NULL" in colClasses FUN = function(h, m, s) times(paste(h, m, s, sep = ":")), FUN2 = function(tt) trunc(tt, "00:00:05"), aggregate = mean) } } \keyword{ts} zoo/man/xblocks.Rd0000644000175100001440000001164014020547743013616 0ustar hornikusers\name{xblocks} \alias{xblocks} \alias{xblocks.default} \alias{xblocks.zoo} \alias{xblocks.ts} \title{ Plot contiguous blocks along x axis. } \description{ Plot contiguous blocks along x axis. A typical use would be to highlight events or periods of missing data. } \usage{ xblocks(x, ...) \S3method{xblocks}{default}(x, y, ..., col = NULL, border = NA, ybottom = par("usr")[3], ytop = ybottom + height, height = diff(par("usr")[3:4]), last.step = median(diff(tail(x)))) \S3method{xblocks}{zoo}(x, y = x, ...) \S3method{xblocks}{ts}(x, y = x, ...) } \arguments{ \item{x, y}{ In the default method, \code{x} gives the ordinates along the x axis and must be in increasing order. \code{y} gives the color values to plot as contiguous blocks. If \code{y} is numeric, data coverage is plotted, by converting it into a logical (\code{!is.na(y)}). Finally, if \code{y} is a function, it is applied to \code{x} (\code{time(x)} in the time series methods). If \code{y} has character (or factor) values, these are interpreted as colors -- and should therefore be color names or hex codes. Missing values in \code{y} are not plotted. The default color is taken from \code{palette()[1]}. If \code{col} is given, this over-rides the block colors given as \code{y}. The \code{ts} and \code{zoo} methods plot the \code{coredata(y)} values against the time index \code{index(x)}. } \item{\dots}{ In the default method, further arguments are graphical parameters passed on to \code{\link[grid]{gpar}}. } \item{col}{ if \code{col} is specified, it determines the colors of the blocks defined by \code{y}. If multiple colors are specified they will be repeated to cover the total number of blocks. } \item{border}{ border color. } \item{ybottom, ytop, height}{ y axis position of the blocks. The default it to fill the whole plot region, but by setting these values one can draw blocks along the top of bottom of the plot. Note that \code{height} is not used directly, it only sets the default value of \code{ytop}. } \item{last.step}{ width (in native units) of the final block. Defaults to the median of the last 5 time steps (assuming steps are regular). } } \details{ Blocks are drawn forward in "time" from the specified x locations, up until the following value. Contiguous blocks are calculated using \code{\link{rle}}. } \author{ Felix Andrews \email{felix@nfrac.org} } \seealso{ \code{\link{rect}} } \examples{ ## example time series: suppressWarnings(RNGversion("3.5.0")) set.seed(0) flow <- ts(filter(rlnorm(200, mean = 1), 0.8, method = "r")) ## highlight values above and below thresholds. ## this draws on top using semi-transparent colors. rgb <- hcl(c(0, 0, 260), c = c(100, 0, 100), l = c(50, 90, 50), alpha = 0.3) plot(flow) xblocks(flow > 30, col = rgb[1]) ## high values red xblocks(flow < 15, col = rgb[3]) ## low value blue xblocks(flow >= 15 & flow <= 30, col = rgb[2]) ## the rest gray ## same thing: plot(flow) xblocks(time(flow), cut(flow, c(0,15,30,Inf), labels = rev(rgb))) ## another approach is to plot blocks underneath without transparency. plot(flow) ## note that 'ifelse' keeps its result as class 'ts' xblocks(ifelse(flow < mean(flow), hcl(0, 0, 90), hcl(0, 80, 70))) ## need to redraw data series on top: lines(flow) box() ## for single series only: plot.default has a panel.first argument plot(time(flow), flow, type = "l", panel.first = xblocks(flow > 20, col = "lightgray")) ## (see also the 'panel' argument for use with multiple series, below) ## insert some missing values flow[c(1:10, 50:80, 100)] <- NA ## the default plot shows data coverage ## (most useful when displaying multiple series, see below) plot(flow) xblocks(flow) ## can also show gaps: plot(flow, type = "s") xblocks(time(flow), is.na(flow), col = "gray") ## Example of alternating colors, here showing calendar months flowdates <- as.Date("2000-01-01") + as.numeric(time(flow)) flowz <- zoo(coredata(flow), flowdates) plot(flowz) xblocks(flowz, months, ## i.e. months(time(flowz)), col = gray.colors(2, start = 0.7), border = "slategray") lines(flowz) ## Example of multiple series. ## set up example data z <- ts(cbind(A = 0:5, B = c(6:7, NA, NA, 10:11), C = c(NA, 13:17))) ## show data coverage only (highlighting gaps) plot(z, panel = function(x, ...) xblocks(x, col = "darkgray")) ## draw gaps in darkgray plot(z, type = "s", panel = function(x, ...) { xblocks(time(x), is.na(x), col = "darkgray") lines(x, ...); points(x) }) ## Example of overlaying blocks from a different series. ## Are US presidential approval ratings linked to sunspot activity? ## Set block height to plot blocks along the bottom. plot(presidents) xblocks(sunspot.year > 50, height = 2) } \keyword{ dplot } zoo/man/na.aggregate.Rd0000644000175100001440000000350611611315753014473 0ustar hornikusers\name{na.aggregate} \alias{na.aggregate} \alias{na.aggregate.default} \title{Replace NA by Aggregation} \description{ Generic function for replacing each \code{NA} with aggregated values. This allows imputing by the overall mean, by monthly means, etc. } \usage{ na.aggregate(object, \dots) \method{na.aggregate}{default}(object, by = 1, \dots, FUN = mean, na.rm = FALSE, maxgap = Inf) } \arguments{ \item{object}{an object.} \item{by}{a grouping variable corresponding to \code{object}, or a function to be applied to \code{time(object)} to generate the groups.} \item{\dots}{further arguments passed to \code{by} if \code{by} is a function.} \item{FUN}{function to apply to the non-missing values in each group defined by \code{by}.} \item{na.rm}{logical. Should any remaining \code{NA}s be removed?} \item{maxgap}{maximum number of consecutive \code{NA}s to fill. Any longer gaps will be left unchanged.} } \value{ An object in which each \code{NA} in the input object is replaced by the mean (or other function) of its group, defined by \code{by}. This is done for each series in a multi-column object. Common choices for the aggregation group are a year, a month, all calendar months, etc. If a group has no non-missing values, the default aggregation function \code{mean} will return \code{NaN}. Specify \code{na.rm = TRUE} to omit such remaining missing values. } \seealso{\code{\link{zoo}}} \examples{ z <- zoo(c(1, NA, 3:9), c(as.Date("2010-01-01") + 0:2, as.Date("2010-02-01") + 0:2, as.Date("2011-01-01") + 0:2)) ## overall mean na.aggregate(z) ## group by months na.aggregate(z, as.yearmon) ## group by calendar months na.aggregate(z, months) ## group by years na.aggregate(z, format, "\%Y") } \keyword{ts} zoo/man/yearmon.Rd0000644000175100001440000001232014275042056013616 0ustar hornikusers\name{yearmon} \alias{yearmon} \alias{as.yearmon} \alias{as.yearmon.default} \alias{as.yearmon.numeric} \alias{as.yearmon.integer} \alias{as.yearmon.date} \alias{as.yearmon.dates} \alias{as.yearmon.Date} \alias{as.yearmon.timeDate} \alias{as.yearmon.jul} \alias{as.yearmon.POSIXt} \alias{as.yearmon.character} \alias{as.yearmon.date} \alias{as.yearmon.factor} \alias{as.Date} \alias{as.Date.numeric} \alias{as.Date.ts} \alias{as.Date.yearmon} \alias{as.POSIXct.yearmon} \alias{as.POSIXlt.yearmon} \alias{as.list.yearmon} \alias{as.numeric.yearmon} \alias{as.character.yearmon} \alias{as.data.frame.yearmon} \alias{c.yearmon} \alias{cycle.yearmon} \alias{format.yearmon} \alias{is.numeric.yearmon} \alias{mean.yearmon} \alias{print.yearmon} \alias{range.yearmon} \alias{summary.yearmon} \alias{unique.yearmon} \alias{[.yearmon} \alias{[[.yearmon} \alias{MATCH.yearmon} \alias{Ops.yearmon} \alias{Summary.yearmon} \alias{Sys.yearmon} \alias{-.yearmon} \alias{xtfrm.yearmon} \title{An Index Class for Monthly Data} \description{ \code{"yearmon"} is a class for representing monthly data. } \usage{ yearmon(x) } \arguments{ \item{x}{numeric (interpreted as being \dQuote{in years}).} } \details{ The \code{"yearmon"} class is used to represent monthly data. Internally it holds the data as year plus 0 for January, 1/12 for February, 2/12 for March and so on in order that its internal representation is the same as \code{ts} class with \code{frequency = 12}. If \code{x} is not in this format it is rounded via \code{floor(12*x + .0001)/12}. There are coercion methods available for various classes including: default coercion to \code{"yearmon"} (which coerces to \code{"numeric"} first) and coercions to and from \code{"yearmon"} to \code{"Date"} (see below), \code{"POSIXct"}, \code{"POSIXlt"}, \code{"numeric"}, \code{"character"} and \code{"jul"}. The last one is from the \code{"tis"} package available on CRAN. In the case of \code{as.yearmon.POSIXt} the conversion is with respect to GMT. (Use \code{as.yearmon(format(...))} for other time zones.) In the case of \code{as.yearmon.character} the \code{format} argument uses the same percent code as \code{"Date"}. These are described in \code{\link{strptime}}. Unlike \code{"Date"} one can specify a year and month with no day. Default formats of \code{"\%Y-\%m"}, \code{"\%Y-\%m-\%d"} and \code{"\%b \%Y"}. There is an \code{is.numeric} method which returns \code{FALSE}. \code{as.Date.yearmon} and \code{as.yearmon.yearqtr} each has an optional second argument of \code{"frac"} which is a number between 0 and 1 inclusive that indicates the fraction of the way through the period that the result represents. The default is 0 which means the beginning of the period. There is also a \code{date} method for \code{as.yearmon} usable with objects created with package \code{date}. \code{Sys.yearmon()} returns the current year/month and methods for \code{min}, \code{max} and \code{range} are defined (by defining a method for \code{Summary}). A \code{yearmon} \code{mean} method is also defined. } \value{ Returns its argument converted to class \code{yearmon}. } \seealso{\code{\link{yearqtr}}, \code{\link{zoo}}, \code{\link{zooreg}}, \code{\link{ts}}} \examples{ Sys.setenv(TZ = "GMT") x <- as.yearmon(2000 + seq(0, 23)/12) x as.yearmon("mar07", "\%b\%y") as.yearmon("2007-03-01") as.yearmon("2007-12") # returned Date is the fraction of the way through # the period given by frac (= 0 by default) as.Date(x) as.Date(x, frac = 1) as.POSIXct(x) # given a Date, x, return the Date of the next Friday nextfri <- function(x) 7 * ceiling(as.numeric(x - 1)/7) + as.Date(1) # given a Date, d, return the same Date in the following month # Note that as.Date.yearmon gives first Date of the month. d <- as.Date("2005-1-1") + seq(0,90,30) next.month <- function(d) as.Date(as.yearmon(d) + 1/12) + as.numeric(d - as.Date(as.yearmon(d))) next.month(d) # 3rd Friday in last month of the quarter of Date x ## first day of last month of quarter y <- as.Date(zoo::as.yearmon(zoo::as.yearqtr(x), frac = 1)) ## number of days to first Friday n <- sapply(y, function(z) which(format(z + 0:6, "\%w") == "5")) - 1 ## add number of days to third Friday y + n + 14 suppressWarnings(RNGversion("3.5.0")) set.seed(1) z <- zoo(rnorm(24), x, frequency = 12) z as.ts(z) ## convert data fram to multivariate monthly "ts" series ## 1.read raw data Lines.raw <- "ID Date Count 123 20 May 1999 1 123 21 May 1999 3 222 1 Feb 2000 2 222 3 Feb 2000 4 " DF <- read.table(text = Lines.raw, skip = 1, col.names = c("ID", "d", "b", "Y", "Count")) ## 2. fix raw date DF$yearmon <- as.yearmon(paste(DF$b, DF$Y), "\%b \%Y") ## 3. aggregate counts over months, convert to zoo and merge over IDs ag <- function(DF) aggregate(zoo(DF$Count), DF$yearmon, sum) z <- do.call("merge.zoo", lapply(split(DF, DF$ID), ag)) ## 4. convert to "zooreg" and then to "ts" frequency(z) <- 12 as.ts(z) xx <- zoo(seq_along(x), x) ## aggregating over year as.year <- function(x) as.numeric(floor(as.yearmon(x))) aggregate(xx, as.year, mean) } \keyword{ts} zoo/man/is.regular.Rd0000644000175100001440000000452013472625011014216 0ustar hornikusers\name{is.regular} \alias{is.regular} \alias{is.regular.zoo} \alias{is.regular.ts} \alias{is.regular.zooreg} \alias{is.regular.default} \title{Check Regularity of a Series} \description{ \code{is.regular} is a regular function for checking whether a series of ordered observations has an underlying regularity or is even strictly regular. } \usage{ is.regular(x, strict = FALSE) } \arguments{ \item{x}{an object (representing a series of ordered observations).} \item{strict}{logical. Should strict regularity be checked? See details.} } \details{ A time series can either be irregular (unequally spaced), strictly regular (equally spaced) or have an underlying regularity, i.e., be created from a regular series by omitting some observations. Here, the latter property is called \emph{regular}. Consequently, regularity follows from strict regularity but not vice versa. \code{is.regular} is a generic function for checking regularity (default) or strict regularity. Currently, it has methods for \code{"ts"} objects (which are always strictly regular), \code{"zooreg"} objects (which are at least regular), \code{"zoo"} objects (which can be either irregular, regular or even strictly regular) and a default method. The latter coerces \code{x} to \code{"zoo"} before checking its regularity. } \value{ A logical is returned indicating whether \code{x} is (strictly) regular. } \seealso{\code{\link{zooreg}}, \code{\link{zoo}}} \examples{ ## checking of a strictly regular zoo series z <- zoo(1:10, seq(2000, 2002.25, by = 0.25), frequency = 4) z class(z) frequency(z) ## extraction of frequency attribute is.regular(z) is.regular(z, strict = TRUE) ## by omitting observations, the series is not strictly regular is.regular(z[-3]) is.regular(z[-3], strict = TRUE) ## checking of a plain zoo series without frequency attribute ## which is in fact regular z <- zoo(1:10, seq(2000, 2002.25, by = 0.25)) z class(z) frequency(z) ## data driven computation of frequency is.regular(z) is.regular(z, strict = TRUE) ## by omitting observations, the series is not strictly regular is.regular(z[-3]) is.regular(z[-3], strict = TRUE) suppressWarnings(RNGversion("3.5.0")) set.seed(1) ## checking of an irregular zoo series z <- zoo(1:10, rnorm(10)) z class(z) frequency(z) ## attempt of data-driven frequency computation is.regular(z) is.regular(z, strict = TRUE) } \keyword{ts} zoo/man/window.zoo.Rd0000644000175100001440000000523213472624624014272 0ustar hornikusers\name{window.zoo} \alias{window.zoo} \alias{window<-.zoo} \title{Extract/Replacing the Time Windows of Objects} \description{ Methods for extracting time windows of \code{"zoo"} objects and replacing it. } \usage{ \method{window}{zoo}(x, index. = index(x), start = NULL, end = NULL, \dots) \method{window}{zoo}(x, index. = index(x), start = NULL, end = NULL, \dots) <- value } \arguments{ \item{x}{an object.} \item{index.}{the index/time window which should be extracted.} \item{start}{an index/time value. Only the indexes in \code{index} which are greater or equal to \code{start} are used. If the index class supports comparisons to character variables, as does \code{"Date"} class, \code{"yearmon"} class, \code{"yearqtr"} class and the \code{chron} package classes \code{"dates"} and \code{"times"} then \code{start} may alternately be a character variable.} \item{end}{an index/time value. Only the indexes in \code{index} which are lower or equal to \code{end} are used. Similar comments about character variables mentioned under \code{start} apply here too.} \item{value}{a suitable value object for use with \code{window(x)}.} \item{\dots}{currently not used.} } \value{ Either the time window of the object is extracted (and hence return a \code{"zoo"} object) or it is replaced. } \seealso{\code{\link{zoo}}} \examples{ suppressWarnings(RNGversion("3.5.0")) set.seed(1) ## zoo example x.date <- as.Date(paste(2003, rep(1:4, 4:1), seq(1,19,2), sep = "-")) x <- zoo(matrix(rnorm(20), ncol = 2), x.date) x window(x, start = as.Date("2003-02-01"), end = as.Date("2003-03-01")) window(x, index = x.date[1:6], start = as.Date("2003-02-01")) window(x, index = x.date[c(4, 8, 10)]) window(x, index = x.date[c(4, 8, 10)]) <- matrix(1:6, ncol = 2) x ## for classes that support comparisons with "character" variables ## start and end may be "character". window(x, start = "2003-02-01") ## zooreg example (with plain numeric index) z <- zooreg(rnorm(10), start = 2000, freq = 4) window(z, start = 2001.75) window(z, start = c(2001, 4)) ## replace data at times of d0 which are in dn d1 <- d0 <- zoo(1:10) + 100 dn <- - head(d0, 4) window(d1, time(dn)) <- coredata(dn) ## if the underlying time index is a float, note that the index may ## print in the same way but actually be different (e.g., differing ## by 0.1 second in this example) zp <- zoo(1:4, as.POSIXct("2000-01-01 00:00:00") + c(-3600, 0, 0.1, 3600)) ## and then the >= start and <= end may not select all intended ## observations and adding/subtracting some "fuzz" may be needed window(zp, end = "2000-01-01 00:00:00") window(zp, end = as.POSIXct("2000-01-01 00:00:00") + 0.5) } \keyword{ts} zoo/man/ORDER.Rd0000644000175100001440000000231311611315753013016 0ustar hornikusers\name{ORDER} \alias{ORDER} \alias{ORDER.default} \title{Ordering Permutation} \description{ \code{ORDER} is a generic function for computing ordering permutations. } \usage{ ORDER(x, \dots) \method{ORDER}{default}(x, \dots, na.last = TRUE, decreasing = FALSE) } \arguments{ \item{x}{an object.} \item{\dots}{further arguments to be passed to methods.} \item{na.last}{for controlling the treatment of \code{NA}s. If \code{TRUE}, missing values in the data are put last; if \code{FALSE}, they are put first; if \code{NA}, they are removed. } \item{decreasing}{logical. Should the sort order be increasing or decreasing?} } \details{ \code{ORDER} is a new generic function which aims at providing the functionality of the non-generic base function \code{\link[base]{order}} for arbitrary objects. Currently, there is only a default method which simply calls \code{\link[base]{order}}. For objects (more precisely if \code{\link[base]{is.object}} is \code{TRUE}) \code{order} leverages the generic \code{xtfrm}. Thus, to assure ordering works, one can supply either a method to \code{xtfrm} or to \code{ORDER} (or both). } \seealso{\code{\link[base]{order}}} \examples{ ORDER(rnorm(5)) } \keyword{manip} zoo/man/lag.zoo.Rd0000644000175100001440000000427511611315753013525 0ustar hornikusers\name{lag.zoo} \alias{lag.zoo} \alias{diff.zoo} \title{Lags and Differences of zoo Objects} \description{ Methods for computing lags and differences of \code{"zoo"} objects. } \usage{ \method{lag}{zoo}(x, k = 1, na.pad = FALSE, \dots) \method{diff}{zoo}(x, lag = 1, differences = 1, arithmetic = TRUE, na.pad = FALSE, \dots) } \arguments{ \item{x}{a \code{"zoo"} object.} \item{k, lag}{For \code{lag} the number of lags (in units of observations). Note the sign of \code{k} behaves as in \code{\link[stats]{lag}}. For \code{diff} it is the number of backward lags used (or if negative the number of forward lags.} \item{differences}{an integer indicating the order of the difference.} \item{arithmetic}{logical. Should arithmetic (or geometric) differences be computed?} \item{na.pad}{logical. If \code{TRUE} it adds any times that would not otherwise have been in the result with a value of \code{NA}. If \code{FALSE} those times are dropped.} \item{\dots}{currently not used.} } \details{ These methods for \code{"zoo"} objects behave analogously to the default methods. The only additional arguments are \code{arithmetic} in \code{diff} \code{na.pad} in \code{lag.zoo} which can also be specified in \code{diff.zoo} as part of the dots. Also, \code{"k"} can be a vector of lags in which case the names of \code{"k"}, if any, are used in naming the result. } \value{ The lagged or differenced \code{"zoo"} object. } \note{ Note the sign of \code{k}: a series lagged by a positive \code{k} is shifted \emph{earlier} in time. \code{lag.zoo} and \code{lag.zooreg} can give different results. For a lag of 1 \code{lag.zoo} moves points to the adjacent time point whereas \code{lag.zooreg} moves the time by \code{deltat}. This implies that a point in a \code{zoo} series cannot be lagged to a time point that is not already in the series whereas this is possible for a \code{zooreg} series. } \seealso{\code{\link{zoo}}, \code{\link[stats]{lag}}, \code{\link[base]{diff}}} \examples{ x <- zoo(11:21) lag(x, k = 1) lag(x, k = -1) # this pairs each value of x with the next or future value merge(x, lag1 = lag(x, k=1)) diff(x^3) diff(x^3, -1) diff(x^3, na.pad = TRUE) } \keyword{ts} zoo/man/rollmean.Rd0000644000175100001440000000607613472624671013777 0ustar hornikusers\name{rollmean} \alias{rollmean} \alias{rollmax} \alias{rollmedian} \alias{rollsum} \alias{rollmeanr} \alias{rollmaxr} \alias{rollmedianr} \alias{rollsumr} \alias{rollmean.zoo} \alias{rollmax.zoo} \alias{rollmedian.zoo} \alias{rollsum.zoo} \alias{rollmean.ts} \alias{rollmax.ts} \alias{rollmedian.ts} \alias{rollsum.ts} \alias{rollmean.default} \alias{rollmax.default} \alias{rollmedian.default} \alias{rollsum.default} \title{Rolling Means/Maximums/Medians/Sums} \description{ Generic functions for computing rolling means, maximums, medians, and sums of ordered observations. } \usage{ rollmean(x, k, fill = if (na.pad) NA, na.pad = FALSE, align = c("center", "left", "right"), ...) rollmax(x, k, fill = if (na.pad) NA, na.pad = FALSE, align = c("center", "left", "right"), ...) rollmedian(x, k, fill = if (na.pad) NA, na.pad = FALSE, align = c("center", "left", "right"), ...) rollsum(x, k, fill = if (na.pad) NA, na.pad = FALSE, align = c("center", "left", "right"), ...) rollmeanr(..., align = "right") rollmaxr(..., align = "right") rollmedianr(..., align = "right") rollsumr(..., align = "right") } \arguments{ \item{x}{an object (representing a series of observations).} \item{k}{integer width of the rolling window. Must be odd for \code{rollmedian}.} \item{fill}{a three-component vector or list (recycled otherwise) providing filling values at the left/within/to the right of the data range. See the \code{fill} argument of \code{\link{na.fill}} for details.} \item{na.pad}{deprecated. Use \code{fill = NA} instead of \code{na.pad = TRUE}.} \item{align}{character specifying whether the index of the result should be left- or right-aligned or centered (default) compared to the rolling window of observations.} \item{\dots}{Further arguments passed to methods.} } \details{ These functions compute rolling means, maximums, medians, and sums respectively and are thus similar to \code{\link{rollapply}} but are optimized for speed. Currently, there are methods for \code{"zoo"} and \code{"ts"} series and default methods. The default method of \code{rollmedian} is an interface to \code{\link{runmed}}. The default methods of \code{rollmean} and \code{rollsum} do not handle inputs that contain \code{NA}s. In such cases, use \code{\link{rollapply}} instead. If \code{x} is of length 0, \code{x} is returned unmodified. } \value{ An object of the same class as \code{x} with the rolling mean/max/median/sum. } \seealso{\code{\link{rollapply}}, \code{\link{zoo}}, \code{\link{na.fill}}} \examples{ suppressWarnings(RNGversion("3.5.0")) set.seed(1) x.Date <- as.Date(paste(2004, rep(1:4, 4:1), sample(1:28, 10), sep = "-")) x <- zoo(rnorm(12), x.Date) ## rolling operations for univariate series rollmean(x, 3) rollmax(x, 3) rollmedian(x, 3) rollsum(x, 3) ## rolling operations for multivariate series xm <- zoo(matrix(1:12, 4, 3), x.Date[1:4]) rollmean(xm, 3) rollmax(xm, 3) rollmedian(xm, 3) rollsum(xm, 3) ## rollapply vs. dedicated rollmean rollapply(xm, 3, mean) # uses rollmean rollapply(xm, 3, function(x) mean(x)) # does not use rollmean } \keyword{ts} zoo/man/frequency.Rd0000644000175100001440000000134411611315753014147 0ustar hornikusers\name{frequency<-} \alias{frequency<-} \alias{frequency<-.zoo} \alias{frequency<-.zooreg} \title{Replacing the Index of Objects} \description{ Generic function for replacing the frequency of an object. } \usage{ frequency(x) <- value } \arguments{ \item{x}{an object.} \item{value}{a frequency.} } \details{ \code{frequency<-} is a generic function for replacing (or assigning) the frequency of an object. Currently, there is a \code{"zooreg"} and a \code{"zoo"} method. In both cases, the \code{value} is assigned to the \code{"frequency"} of the object if it complies with the \code{index(x)}. } \seealso{\code{\link{zooreg}}, \code{\link{index}}} \examples{ z <- zooreg(1:5) z as.ts(z) frequency(z) <- 3 z as.ts(z) } \keyword{ts} zoo/man/rollapply.Rd0000644000175100001440000002771413735723543014206 0ustar hornikusers\name{rollapply} \alias{rollapply} \alias{rollapplyr} \alias{rollapply.default} \alias{rollapply.ts} \alias{rollapply.zoo} \title{Apply Rolling Functions} \description{ A generic function for applying a function to rolling margins of an array. } \usage{ rollapply(data, \dots) \method{rollapply}{ts}(data, \dots) \method{rollapply}{zoo}(data, width, FUN, \dots, by = 1, by.column = TRUE, fill = if (na.pad) NA, na.pad = FALSE, partial = FALSE, align = c("center", "left", "right"), coredata = TRUE) \method{rollapply}{default}(data, \dots) rollapplyr(\dots, align = "right") } \arguments{ \item{data}{the data to be used (representing a series of observations).} \item{width}{numeric vector or list. In the simplest case this is an integer specifying the window width (in numbers of observations) which is aligned to the original sample according to the \code{align} argument. Alternatively, \code{width} can be a list regarded as offsets compared to the current time, see below for details.} \item{FUN}{the function to be applied.} \item{\dots}{optional arguments to \code{FUN}.} \item{by}{calculate FUN at every \code{by}-th time point rather than every point. \code{by} is only used if \code{width} is length 1 and either a plain scalar or a list.} \item{by.column}{logical. If \code{TRUE}, \code{FUN} is applied to each column separately.} \item{fill}{a three-component vector or list (recycled otherwise) providing filling values at the left/within/to the right of the data range. See the \code{fill} argument of \code{\link{na.fill}} for details.} \item{na.pad}{deprecated. Use \code{fill = NA} instead of \code{na.pad = TRUE}.} \item{partial}{logical or numeric. If \code{FALSE} (default) then \code{FUN} is only applied when all indexes of the rolling window are within the observed time range. If \code{TRUE}, then the subset of indexes that are in range are passed to \code{FUN}. A numeric argument to \code{partial} can be used to determin the minimal window size for partial computations. See below for more details.} \item{align}{specifyies whether the index of the result should be left- or right-aligned or centered (default) compared to the rolling window of observations. This argument is only used if \code{width} represents widths.} \item{coredata}{logical. Should only the \code{coredata(data)} be passed to every \code{width} window? If set to \code{FALSE} the full zoo series is used.} } \details{ If \code{width} is a plain numeric vector its elements are regarded as widths to be interpreted in conjunction with \code{align} whereas if \code{width} is a list its components are regarded as offsets. In the above cases if the length of \code{width} is 1 then \code{width} is recycled for every \code{by}-th point. If \code{width} is a list its components represent integer offsets such that the i-th component of the list refers to time points at positions \code{i + width[[i]]}. If any of these points are below 1 or above the length of \code{index(data)} then \code{FUN} is not evaluated for that point unless \code{partial = TRUE} and in that case only the valid points are passed. The rolling function can also be applied to partial windows by setting \code{partial = TRUE} For example, if \code{width = 3, align = "right"} then for the first point just that point is passed to \code{FUN} since the two points to its left are out of range. For the same example, if \code{partial = FALSE} then \code{FUN} is not invoked at all for the first two points. If \code{partial} is a numeric then it specifies the minimum number of offsets that must be within range. Negative \code{partial} is interpreted as \code{FALSE}. If \code{width} is a scalar then \code{partial = TRUE} and \code{fill = NA} are mutually exclusive but if offsets are specified for the \code{width} and 0 is not among the offsets then the output will be shorter than the input even if \code{partial = TRUE} is specified. In that case it may still be useful to specify \code{fill} in addition to \code{partial}. If \code{FUN} is \code{mean}, \code{max} or \code{median} and \code{by.column} is \code{TRUE} and width is a plain scalar and there are no other arguments then special purpose code is used to enhance performance. Also in the case of \code{mean} such special purpose code is only invoked if the \code{data} argument has no \code{NA} values. See \code{\link{rollmean}}, \code{\link{rollmax}} and \code{\link{rollmedian}} for more details. Currently, there are methods for \code{"zoo"} and \code{"ts"} series and \code{"default"} method for ordinary vectors and matrices. \code{rollapplyr} is a wrapper around \code{rollapply} that uses a default of \code{align = "right"}. If \code{data} is of length 0, \code{data} is returned unmodified. } \value{ A object of the same class as \code{data} with the results of the rolling function. } \seealso{\code{\link{rollmean}}} \examples{ suppressWarnings(RNGversion("3.5.0")) set.seed(1) ## rolling mean z <- zoo(11:15, as.Date(31:35)) rollapply(z, 2, mean) ## non-overlapping means z2 <- zoo(rnorm(6)) rollapply(z2, 3, mean, by = 3) # means of nonoverlapping groups of 3 aggregate(z2, c(3,3,3,6,6,6), mean) # same ## optimized vs. customized versions rollapply(z2, 3, mean) # uses rollmean which is optimized for mean rollmean(z2, 3) # same rollapply(z2, 3, (mean)) # does not use rollmean ## rolling regression: ## set up multivariate zoo series with ## number of UK driver deaths and lags 1 and 12 seat <- as.zoo(log(UKDriverDeaths)) time(seat) <- as.yearmon(time(seat)) seat <- merge(y = seat, y1 = lag(seat, k = -1), y12 = lag(seat, k = -12), all = FALSE) ## run a rolling regression with a 3-year time window ## (similar to a SARIMA(1,0,0)(1,0,0)_12 fitted by OLS) rr <- rollapply(seat, width = 36, FUN = function(z) coef(lm(y ~ y1 + y12, data = as.data.frame(z))), by.column = FALSE, align = "right") ## plot the changes in coefficients ## showing the shifts after the oil crisis in Oct 1973 ## and after the seatbelt legislation change in Jan 1983 plot(rr) ## rolling mean by time window (e.g., 3 days) rather than ## by number of observations (e.g., when these are unequally spaced): # ## - test data tt <- as.Date("2000-01-01") + c(1, 2, 5, 6, 7, 8, 10) z <- zoo(seq_along(tt), tt) ## - fill it out to a daily series, zm, using NAs ## using a zero width zoo series g on a grid g <- zoo(, seq(start(z), end(z), "day")) zm <- merge(z, g) ## - 3-day rolling mean rollapply(zm, 3, mean, na.rm = TRUE, fill = NA) ## ## - without expansion to regular grid: find interval widths ## that encompass the previous 3 days for each Date w <- seq_along(tt) - findInterval(tt - 3, tt) ## a solution to computing the widths 'w' that is easier to read but slower ## w <- sapply(tt, function(x) sum(tt >= x - 2 & tt <= x)) ## ## - rolling sum from 3-day windows ## without vs. with expansion to regular grid rollapplyr(z, w, sum) rollapplyr(zm, 3, sum, partial = TRUE, na.rm = TRUE) ## rolling weekly sums (with some missing dates) z <- zoo(1:11, as.Date("2016-03-09") + c(0:7, 9:10, 12)) weeksum <- function(z) sum(z[time(z) > max(time(z)) - 7]) zs <- rollapplyr(z, 7, weeksum, fill = NA, coredata = FALSE) merge(value = z, weeksum = zs) ## replicate cumsum with either 'partial' or vector width 'k' cumsum(1:10) rollapplyr(1:10, 10, sum, partial = TRUE) rollapplyr(1:10, 1:10, sum) ## different values of rule argument z <- zoo(c(NA, NA, 2, 3, 4, 5, NA)) rollapply(z, 3, sum, na.rm = TRUE) rollapply(z, 3, sum, na.rm = TRUE, fill = NULL) rollapply(z, 3, sum, na.rm = TRUE, fill = NA) rollapply(z, 3, sum, na.rm = TRUE, partial = TRUE) # this will exclude time points 1 and 2 # It corresponds to align = "right", width = 3 rollapply(zoo(1:8), list(seq(-2, 0)), sum) # but this will include points 1 and 2 rollapply(zoo(1:8), list(seq(-2, 0)), sum, partial = 1) rollapply(zoo(1:8), list(seq(-2, 0)), sum, partial = 0) # so will this rollapply(zoo(1:8), list(seq(-2, 0)), sum, fill = NA) # by = 3, align = "right" L <- rep(list(NULL), 8) L[seq(3, 8, 3)] <- list(seq(-2, 0)) str(L) rollapply(zoo(1:8), L, sum) rollapply(zoo(1:8), list(0:2), sum, fill = 1:3) rollapply(zoo(1:8), list(0:2), sum, fill = 3) L2 <- rep(list(-(2:0)), 10) L2[5] <- list(NULL) str(L2) rollapply(zoo(1:10), L2, sum, fill = "extend") rollapply(zoo(1:10), L2, sum, fill = list("extend", NULL)) rollapply(zoo(1:10), L2, sum, fill = list("extend", NA)) rollapply(zoo(1:10), L2, sum, fill = NA) rollapply(zoo(1:10), L2, sum, fill = 1:3) rollapply(zoo(1:10), L2, sum, partial = TRUE) rollapply(zoo(1:10), L2, sum, partial = TRUE, fill = 99) rollapply(zoo(1:10), list(-1), sum, partial = 0) rollapply(zoo(1:10), list(-1), sum, partial = TRUE) rollapply(zoo(cbind(a = 1:6, b = 11:16)), 3, rowSums, by.column = FALSE) # these two are the same rollapply(zoo(cbind(a = 1:6, b = 11:16)), 3, sum) rollapply(zoo(cbind(a = 1:6, b = 11:16)), 3, colSums, by.column = FALSE) # these two are the same rollapply(zoo(1:6), 2, sum, by = 2, align = "right") aggregate(zoo(1:6), c(2, 2, 4, 4, 6, 6), sum) # these two are the same rollapply(zoo(1:3), list(-1), c) lag(zoo(1:3), -1) # these two are the same rollapply(zoo(1:3), list(1), c) lag(zoo(1:3)) # these two are the same rollapply(zoo(1:5), list(c(-1, 0, 1)), sum) rollapply(zoo(1:5), 3, sum) # these two are the same rollapply(zoo(1:5), list(0:2), sum) rollapply(zoo(1:5), 3, sum, align = "left") # these two are the same rollapply(zoo(1:5), list(-(2:0)), sum) rollapply(zoo(1:5), 3, sum, align = "right") # these two are the same rollapply(zoo(1:6), list(NULL, NULL, -(2:0)), sum) rollapply(zoo(1:6), 3, sum, by = 3, align = "right") # these two are the same rollapply(zoo(1:5), list(c(-1, 1)), sum) rollapply(zoo(1:5), 3, function(x) sum(x[-2])) # these two are the same rollapply(1:5, 3, rev) embed(1:5, 3) # these four are the same x <- 1:6 rollapply(c(0, 0, x), 3, sum, align = "right") - x rollapply(x, 3, sum, partial = TRUE, align = "right") - x rollapply(x, 3, function(x) sum(x[-3]), partial = TRUE, align = "right") rollapply(x, list(-(2:1)), sum, partial = 0) # same as Matlab's buffer(x, n, p) for valid non-negative p # See http://www.mathworks.com/help/toolbox/signal/buffer.html x <- 1:30; n <- 7; p <- 3 t(rollapply(c(rep(0, p), x, rep(0, n-p)), n, by = n-p, c)) # these three are the same y <- 10 * seq(8); k <- 4; d <- 2 # 1 # from http://ucfagls.wordpress.com/2011/06/14/embedding-a-time-series-with-time-delay-in-r-part-ii/ Embed <- function(x, m, d = 1, indices = FALSE, as.embed = TRUE) { n <- length(x) - (m-1)*d X <- seq_along(x) if(n <= 0) stop("Insufficient observations for the requested embedding") out <- matrix(rep(X[seq_len(n)], m), ncol = m) out[,-1] <- out[,-1, drop = FALSE] + rep(seq_len(m - 1) * d, each = nrow(out)) if(as.embed) out <- out[, rev(seq_len(ncol(out)))] if(!indices) out <- matrix(x[out], ncol = m) out } Embed(y, k, d) # 2 rollapply(y, list(-d * seq(0, k-1)), c) # 3 rollapply(y, d*k-1, function(x) x[d * seq(k-1, 0) + 1]) ## mimic convolve() using rollapplyr() A <- 1:4 B <- 5:8 ## convolve(..., type = "open") cross <- function(x) x %*% tail(B, length(x)) rollapplyr(c(A, 0*B[-1]), length(B), cross, partial = TRUE) convolve(A, B, type = "open") # convolve(..., type = "filter") rollapplyr(A, length(B), cross) convolve(A, B, type = "filter") # weighted sum including partials near ends, keeping ## alignment with wts correct points <- zoo(cbind(lon = c(11.8300715, 11.8296697, 11.8268708, 11.8267236, 11.8249612, 11.8251062), lat = c(48.1099048, 48.10884, 48.1067431, 48.1066077, 48.1037673, 48.103318), dist = c(46.8463805878941, 33.4921440879536, 10.6101735030534, 18.6085009578724, 6.97253109610173, 9.8912817449265))) mysmooth <- function(z, wts = c(0.3, 0.4, 0.3)) { notna <- !is.na(z) sum(z[notna] * wts[notna]) / sum(wts[notna]) } points2 <- points points2[, 1:2] <- rollapply(rbind(NA, coredata(points)[, 1:2], NA), 3, mysmooth) points2 } \keyword{iteration} \keyword{array} \keyword{ts} zoo/man/index.Rd0000644000175100001440000000325713472624771013274 0ustar hornikusers\name{index} \alias{index} \alias{index.default} \alias{index.zoo} \alias{index.ts} \alias{time.zoo} \alias{index<-} \alias{index<-.zoo} \alias{time<-} \alias{time<-.zoo} \alias{start.zoo} \alias{end.zoo} \title{Extracting/Replacing the Index of Objects} \description{ Generic functions for extracting the index of an object and replacing it. } \usage{ index(x, \dots) index(x) <- value } \arguments{ \item{x}{an object.} \item{\dots}{further arguments passed to methods.} \item{value}{an ordered vector of the same length as the \code{"index"} attribute of \code{x}.} } \details{ \code{index} is a generic function for extracting the index of objects, currently it has a default method and a method for \code{\link{zoo}} objects which is the same as the \code{\link{time}} method for \code{\link{zoo}} objects. Another pair of generic functions provides replacing the \code{index} or \code{time} attribute. Methods are available for \code{"zoo"} objects only, see examples below. The start and end of the index/time can be queried by using the methods of \code{start} and \code{end}. } \seealso{\code{\link{time}}, \code{\link{zoo}}} \examples{ suppressWarnings(RNGversion("3.5.0")) set.seed(1) x.date <- as.Date(paste(2003, 2, c(1, 3, 7, 9, 14), sep = "-")) x <- zoo(rnorm(5), x.date) ## query index/time of a zoo object index(x) time(x) ## change class of index from Date to POSIXct ## relative to current time zone x index(x) <- as.POSIXct(format(time(x)),tz="") x ## replace index/time of a zoo object index(x) <- 1:5 x time(x) <- 6:10 x ## query start and end of a zoo object start(x) end(x) ## query index of a usual matrix xm <- matrix(rnorm(10), ncol = 2) index(xm) } \keyword{ts} zoo/DESCRIPTION0000644000175100001440000000342414415770740012621 0ustar hornikusersPackage: zoo Version: 1.8-12 Date: 2023-04-11 Title: S3 Infrastructure for Regular and Irregular Time Series (Z's Ordered Observations) Authors@R: c(person(given = "Achim", family = "Zeileis", role = c("aut", "cre"), email = "Achim.Zeileis@R-project.org", comment = c(ORCID = "0000-0003-0918-3766")), person(given = "Gabor", family = "Grothendieck", role = "aut", email = "ggrothendieck@gmail.com"), person(given = c("Jeffrey", "A."), family = "Ryan", role = "aut", email = "jeff.a.ryan@gmail.com"), person(given = c("Joshua", "M."), family = "Ulrich", role = "ctb", email = "josh.m.ulrich@gmail.com"), person(given = "Felix", family = "Andrews", role = "ctb", email = "felix@nfrac.org")) Description: An S3 class with methods for totally ordered indexed observations. It is particularly aimed at irregular time series of numeric vectors/matrices and factors. zoo's key design goals are independence of a particular index/date/time class and consistency with ts and base R by providing methods to extend standard generics. Depends: R (>= 3.1.0), stats Suggests: AER, coda, chron, ggplot2 (>= 3.0.0), mondate, scales, stinepack, strucchange, timeDate, timeSeries, tis, tseries, xts Imports: utils, graphics, grDevices, lattice (>= 0.20-27) License: GPL-2 | GPL-3 URL: https://zoo.R-Forge.R-project.org/ NeedsCompilation: yes Packaged: 2023-04-11 21:24:32 UTC; zeileis Author: Achim Zeileis [aut, cre] (), Gabor Grothendieck [aut], Jeffrey A. Ryan [aut], Joshua M. Ulrich [ctb], Felix Andrews [ctb] Maintainer: Achim Zeileis Repository: CRAN Date/Publication: 2023-04-13 12:13:20 UTC zoo/build/0000755000175100001440000000000014415350017012176 5ustar hornikuserszoo/build/vignette.rds0000644000175100001440000000077714415350017014550 0ustar hornikusersTMO@5 $[* '+.7 ]aٍצ*{o1(8№1:+ҨO:XNʡ,Z:R?FGXø a2r L@2G5% !0f@n뜖g00;/%*`w4 +(#rV\hN.n*?JV;|Eחj/ Vböa j,u;$ =X6PB|ówHf l mgAԭh8LRt{x09x{oBP_ЋEzӭ(P5ܸE~zoo/tests/0000755000175100001440000000000014415350020012233 5ustar hornikuserszoo/tests/vignette-zoo-quickref.R0000644000175100001440000002220013444020272016617 0ustar hornikusers################################################### ### chunk number 1: preliminaries ################################################### library("zoo") library("tseries") online <- FALSE ## if set to FALSE the local copy of ## is used instead of get.hist.quote() options(prompt = "R> ") Sys.setenv(TZ = "GMT") suppressWarnings(RNGversion("3.5.0")) ################################################### ### chunk number 2: read.zoo ################################################### inrusd <- read.zoo(system.file("doc", "demo1.txt", package = "zoo"), sep = "|", format="%d %b %Y") ################################################### ### chunk number 3: read.table ################################################### tmp <- read.table(system.file("doc", "demo2.txt", package = "zoo"), sep = ",") z <- zoo(tmp[, 3:4], as.Date(as.character(tmp[, 2]), format="%d %b %Y")) colnames(z) <- c("Nifty", "Junior") ################################################### ### chunk number 4: extract dates ################################################### time(z) ################################################### ### chunk number 5: start and end ################################################### start(z) end(inrusd) ################################################### ### chunk number 6: convert to plain matrix ################################################### plain <- coredata(z) str(plain) ################################################### ### chunk number 7: intersection ################################################### m <- merge(inrusd, z, all = FALSE) ################################################### ### chunk number 8: union ################################################### m <- merge(inrusd, z) ################################################### ### chunk number 9: merge with lag ################################################### merge(inrusd, lag(inrusd, -1)) ################################################### ### chunk number 10: plotting1 ################################################### plot(m) ################################################### ### chunk number 11: plotting2 ################################################### plot(m[, 2:3], plot.type = "single", col = c("red", "blue"), lwd = 2) ################################################### ### chunk number 12: select range of dates ################################################### window(z, start = as.Date("2005-02-15"), end = as.Date("2005-02-28")) ################################################### ### chunk number 13: select one date ################################################### m[as.Date("2005-03-10")] ################################################### ### chunk number 14: impute NAs by interpolation ################################################### interpolated <- na.approx(m) ################################################### ### chunk number 15: impute NAs by LOCF ################################################### m <- na.locf(m) m ################################################### ### chunk number 16: compute returns ################################################### prices2returns <- function(x) 100*diff(log(x)) ################################################### ### chunk number 17: column-wise returns ################################################### r <- prices2returns(m) ################################################### ### chunk number 18: rolling standard deviations ################################################### rollapply(r, 10, sd) ################################################### ### chunk number 19: last day of month ################################################### prices2returns(aggregate(m, as.yearmon, tail, 1)) ################################################### ### chunk number 20: last day of week ################################################### nextfri <- function(x) 7 * ceiling(as.numeric(x-5+4) / 7) + as.Date(5-4) prices2returns(aggregate(na.locf(m), nextfri, tail, 1)) ################################################### ### chunk number 21: four second mark ################################################### zsec <- structure(1:10, index = structure(c(1234760403.968, 1234760403.969, 1234760403.969, 1234760405.029, 1234760405.029, 1234760405.03, 1234760405.03, 1234760405.072, 1234760405.073, 1234760405.073 ), class = c("POSIXt", "POSIXct"), tzone = ""), class = "zoo") to4sec <- function(x) as.POSIXct(4*ceiling(as.numeric(x)/4), origin = "1970-01-01") aggregate(zsec, to4sec, tail, 1) ################################################### ### chunk number 22: one second grid ################################################### # tmp is zsec with time discretized into one second bins tmp <- zsec st <- start(tmp) Epoch <- st - as.numeric(st) time(tmp) <- as.integer(time(tmp) + 1e-7) + Epoch # find index of last value in each one second interval ix <- !duplicated(time(tmp), fromLast = TRUE) # merge with grid merge(tmp[ix], zoo(, seq(start(tmp), end(tmp), "sec"))) # Here is a function which generalizes the above: intraday.discretise <- function(b, Nsec) { st <- start(b) time(b) <- Nsec * as.integer(time(b)+1e-7) %/% Nsec + st - as.numeric(st) ix <- !duplicated(time(b), fromLast = TRUE) merge(b[ix], zoo(, seq(start(b), end(b), paste(Nsec, "sec")))) } intraday.discretise(zsec, 1) ################################################### ### chunk number 23: tseries ################################################### library("tseries") ################################################### ### chunk number 24: data handling if offline ################################################### if(online) { sunw <- get.hist.quote(instrument = "SUNW", start = "2004-01-01", end = "2004-12-31") sunw2 <- get.hist.quote(instrument = "SUNW", start = "2004-01-01", end = "2004-12-31", compression = "m", quote = "Close") eur.usd <- get.hist.quote(instrument = "EUR/USD", provider = "oanda", start = "2004-01-01", end = "2004-12-31") save(sunw, sunw2, eur.usd, file = "sunw.rda") } else { load(system.file("doc", "sunw.rda", package = "zoo")) } ################################################### ### chunk number 25: get.hist.quote daily series eval=FALSE ################################################### ## sunw <- get.hist.quote(instrument = "SUNW", start = "2004-01-01", end = "2004-12-31") ################################################### ### chunk number 26: get.hist.quote monthly series eval=FALSE ################################################### ## sunw2 <- get.hist.quote(instrument = "SUNW", start = "2004-01-01", end = "2004-12-31", ## compression = "m", quote = "Close") ################################################### ### chunk number 27: change index to yearmon ################################################### time(sunw2) <- as.yearmon(time(sunw2)) ################################################### ### chunk number 28: compute same series via aggregate ################################################### sunw3 <- aggregate(sunw[, "Close"], as.yearmon, tail, 1) ################################################### ### chunk number 29: compute returns ################################################### r <- prices2returns(sunw3) ################################################### ### chunk number 30: get.hist.quote oanda eval=FALSE ################################################### ## eur.usd <- get.hist.quote(instrument = "EUR/USD", provider = "oanda", start = "2004-01-01", end = "2004-12-31") ################################################### ### chunk number 31: is.weekend convenience function ################################################### is.weekend <- function(x) ((as.numeric(x)-2) %% 7) < 2 ################################################### ### chunk number 32: omit weekends ################################################### eur.usd <- eur.usd[!is.weekend(time(eur.usd))] ################################################### ### chunk number 33: is.weekend based on POSIXlt ################################################### is.weekend <- function(x) { x <- as.POSIXlt(x) x$wday > 5 | x$wday < 1 } ################################################### ### chunk number 34: summaries ################################################### date1 <- seq(as.Date("2001-01-01"), as.Date("2002-12-1"), by = "day") len1 <- length(date1) set.seed(1) # to make it reproducible data1 <- zoo(rnorm(len1), date1) # quarterly summary data1q.mean <- aggregate(data1, as.yearqtr, mean) data1q.sd <- aggregate(data1, as.yearqtr, sd) head(cbind(mean = data1q.mean, sd = data1q.sd), main = "Quarterly") # weekly summary - week ends on tuesday # Given a date find the next Tuesday. # Based on formula in Prices and Returns section. nexttue <- function(x) 7 * ceiling(as.numeric(x - 2 + 4)/7) + as.Date(2 - 4) data1w <- cbind( mean = aggregate(data1, nexttue, mean), sd = aggregate(data1, nexttue, sd) ) head(data1w) ### ALTERNATIVE ### # Create function ag like aggregate but takes vector of # function names. FUNs <- c(mean, sd) ag <- function(z, by, FUNs) { f <- function(f) aggregate(z, by, f) do.call(cbind, sapply(FUNs, f, simplify = FALSE)) } data1q <- ag(data1, as.yearqtr, c("mean", "sd")) data1w <- ag(data1, nexttue, c("mean", "sd")) head(data1q) head(data1w) zoo/tests/na.fill.R0000644000175100001440000000243313271716002013710 0ustar hornikuserslibrary("zoo") target <- c(100, 1, 200, 2, 300) current <- na.fill0(c(NA, 1, NA, 2, NA), c(100, 200, 300)) identical(target, current) target <- structure(c(100, 1, 200, 2), na.action = 5L) current <- na.fill0(c(NA, 1, NA, 2, NA), list(100, 200, NULL)) identical(target, current) target <- structure(c(1, 1, 200, 2), na.action = 5L) current <- na.fill0(c(NA, 1, NA, 2, NA), list("extend", 200, NULL)) identical(target, current) target <- c(1, 1, 200, 2, 2) current <- na.fill0(c(NA, 1, NA, 2, NA), list("extend", 200, "extend")) identical(target, current) target <- structure(c(1, 2), na.action = c(1L, 3L, 5L)) current <- na.fill0(c(NA, 1, NA, 2, NA), list()) identical(target, current) target <- NULL current <- na.fill0(NULL, list(1)) identical(target, current) target <- 1 current <- na.fill0(1, list(1)) identical(target, current) target <- 1 current <- na.fill0(1, 2) identical(target, current) target <- structure(c(17650, 17650, 0, 17651, 17651), class = "Date") current <- na.fill0(as.Date("2018-04-28") + c(NA, 1, NA, 2, NA), list("extend", as.Date(0))) identical(target, current) target <- structure(c(0, 17650, 0, 17651, 0), class = "Date") current <- na.fill0(as.Date("2018-04-28") + c(NA, 1, NA, 2, NA), as.Date(0)) identical(target, current) zoo/tests/Examples/0000755000175100001440000000000013472721645014032 5ustar hornikuserszoo/tests/Examples/zoo-Ex.Rout.save0000644000175100001440000031702614415347773017040 0ustar hornikusers R version 4.2.2 Patched (2022-11-10 r83330) -- "Innocent and Trusting" Copyright (C) 2022 The R Foundation for Statistical Computing Platform: x86_64-pc-linux-gnu (64-bit) R is free software and comes with ABSOLUTELY NO WARRANTY. You are welcome to redistribute it under certain conditions. Type 'license()' or 'licence()' for distribution details. Natural language support but running in an English locale R is a collaborative project with many contributors. Type 'contributors()' for more information and 'citation()' on how to cite R or R packages in publications. Type 'demo()' for some demos, 'help()' for on-line help, or 'help.start()' for an HTML browser interface to help. Type 'q()' to quit R. > pkgname <- "zoo" > source(file.path(R.home("share"), "R", "examples-header.R")) > options(warn = 1) > library('zoo') Attaching package: ‘zoo’ The following objects are masked from ‘package:base’: as.Date, as.Date.numeric > > base::assign(".oldSearch", base::search(), pos = 'CheckExEnv') > base::assign(".old_wd", base::getwd(), pos = 'CheckExEnv') > cleanEx() > nameEx("MATCH") > ### * MATCH > > flush(stderr()); flush(stdout()) > > ### Name: MATCH > ### Title: Value Matching > ### Aliases: MATCH MATCH.default MATCH.times MATCH.timeDate MATCH.Date > ### MATCH.POSIXct MATCH.POSIXlt > ### Keywords: manip > > ### ** Examples > > MATCH(1:5, 2:3) [1] NA 1 2 NA NA > > > > cleanEx() > nameEx("ORDER") > ### * ORDER > > flush(stderr()); flush(stdout()) > > ### Name: ORDER > ### Title: Ordering Permutation > ### Aliases: ORDER ORDER.default > ### Keywords: manip > > ### ** Examples > > ORDER(rnorm(5)) [1] 3 1 2 5 4 > > > > cleanEx() > nameEx("aggregate.zoo") > ### * aggregate.zoo > > flush(stderr()); flush(stdout()) > > ### Name: aggregate.zoo > ### Title: Compute Summary Statistics of zoo Objects > ### Aliases: aggregate.zoo split.zoo > ### Keywords: ts > > ### ** Examples > > ## averaging over values in a month: > # x.date is jan 1,3,5,7; feb 9,11,13; mar 15,17,19 > x.date <- as.Date(paste(2004, rep(1:4, 4:1), seq(1,20,2), sep = "-")); x.date [1] "2004-01-01" "2004-01-03" "2004-01-05" "2004-01-07" "2004-02-09" [6] "2004-02-11" "2004-02-13" "2004-03-15" "2004-03-17" "2004-04-19" > x <- zoo(rnorm(12), x.date); x 2004-01-01 2004-01-03 2004-01-05 2004-01-07 2004-02-09 2004-02-11 2004-02-13 -0.6264538 0.1836433 -0.8356286 1.5952808 0.3295078 -0.8204684 0.4874291 2004-03-15 2004-03-17 2004-04-19 0.7383247 0.5757814 -0.3053884 > # coarser dates - jan 1 (4 times), feb 1 (3 times), mar 1 (3 times) > x.date2 <- as.Date(paste(2004, rep(1:4, 4:1), 1, sep = "-")); x.date2 [1] "2004-01-01" "2004-01-01" "2004-01-01" "2004-01-01" "2004-02-01" [6] "2004-02-01" "2004-02-01" "2004-03-01" "2004-03-01" "2004-04-01" > x2 <- aggregate(x, x.date2, mean); x2 2004-01-01 2004-02-01 2004-03-01 2004-04-01 0.079210426 -0.001177187 0.657053028 -0.305388387 > # same - uses as.yearmon > x2a <- aggregate(x, as.Date(as.yearmon(time(x))), mean); x2a 2004-01-01 2004-02-01 2004-03-01 2004-04-01 0.079210426 -0.001177187 0.657053028 -0.305388387 > # same - uses by function > x2b <- aggregate(x, function(tt) as.Date(as.yearmon(tt)), mean); x2b 2004-01-01 2004-02-01 2004-03-01 2004-04-01 0.079210426 -0.001177187 0.657053028 -0.305388387 > # same - uses cut > x2c <- aggregate(x, as.Date(cut(time(x), "month")), mean); x2c 2004-01-01 2004-02-01 2004-03-01 2004-04-01 0.079210426 -0.001177187 0.657053028 -0.305388387 > # almost same but times of x2d have yearmon class rather than Date class > x2d <- aggregate(x, as.yearmon, mean); x2d Jan 2004 Feb 2004 Mar 2004 Apr 2004 0.079210426 -0.001177187 0.657053028 -0.305388387 > > # compare time series > plot(x) > lines(x2, col = 2) > > ## aggregate a daily time series to a quarterly series > # create zoo series > tt <- as.Date("2000-1-1") + 0:300 > z.day <- zoo(0:300, tt) > > # function which returns corresponding first "Date" of quarter > first.of.quarter <- function(tt) as.Date(as.yearqtr(tt)) > > # average z over quarters > # 1. via "yearqtr" index (regular) > # 2. via "Date" index (not regular) > z.qtr1 <- aggregate(z.day, as.yearqtr, mean) > z.qtr2 <- aggregate(z.day, first.of.quarter, mean) > > # The last one used the first day of the quarter but suppose > # we want the first day of the quarter that exists in the series > # (and the series does not necessarily start on the first day > # of the quarter). > z.day[!duplicated(as.yearqtr(time(z.day)))] 2000-01-01 2000-04-01 2000-07-01 2000-10-01 0 91 182 274 > > # This is the same except it uses the last day of the quarter. > # It requires R 2.6.0 which introduced the fromLast= argument. > ## Not run: > ##D z.day[!duplicated(as.yearqtr(time(z.day)), fromLast = TRUE)] > ## End(Not run) > > # The aggregated series above are of class "zoo" (because z.day > # was "zoo"). To create a regular series of class "zooreg", > # the frequency can be automatically chosen > zr.qtr1 <- aggregate(z.day, as.yearqtr, mean, regular = TRUE) > # or specified explicitely > zr.qtr2 <- aggregate(z.day, as.yearqtr, mean, frequency = 4) > > > ## aggregate on month and extend to monthly time series > if(require(chron)) { + y <- zoo(matrix(11:15, nrow = 5, ncol = 2), chron(c(15, 20, 80, 100, 110))) + colnames(y) <- c("A", "B") + + # aggregate by month using first of month as times for coarser series + # using first day of month as repesentative time + y2 <- aggregate(y, as.Date(as.yearmon(time(y))), head, 1) + + # fill in missing months by merging with an empty series containing + # a complete set of 1st of the months + yrt2 <- range(time(y2)) + y0 <- zoo(,seq(from = yrt2[1], to = yrt2[2], by = "month")) + merge(y2, y0) + } Loading required package: chron A B 1970-01-01 11 11 1970-02-01 NA NA 1970-03-01 13 13 1970-04-01 14 14 > > # given daily series keep only first point in each month at > # day 21 or more > z <- zoo(101:200, as.Date("2000-01-01") + seq(0, length = 100, by = 2)) > zz <- z[as.numeric(format(time(z), "%d")) >= 21] > zz[!duplicated(as.yearmon(time(zz)))] 2000-01-21 2000-02-22 2000-03-21 2000-04-22 2000-05-22 2000-06-21 111 127 141 157 172 187 > > # same except times are of "yearmon" class > aggregate(zz, as.yearmon, head, 1) Jan 2000 Feb 2000 Mar 2000 Apr 2000 May 2000 Jun 2000 111 127 141 157 172 187 > > # aggregate POSIXct seconds data every 10 minutes > Sys.setenv(TZ = "GMT") > tt <- seq(10, 2000, 10) > x <- zoo(tt, structure(tt, class = c("POSIXt", "POSIXct"))) > aggregate(x, time(x) - as.numeric(time(x)) %% 600, mean) 1970-01-01 00:00:00 1970-01-01 00:10:00 1970-01-01 00:20:00 1970-01-01 00:30:00 300 895 1495 1900 > > # aggregate weekly series to a series with frequency of 52 per year > suppressWarnings(RNGversion("3.5.0")) > set.seed(1) > z <- zooreg(1:100 + rnorm(100), start = as.Date("2001-01-01"), deltat = 7) > > # new.freq() converts dates to a grid of freq points per year > # yd is sequence of dates of firsts of years > # yy is years of the same sequence > # last line interpolates so dates, d, are transformed to year + frac of year > # so first week of 2001 is 2001.0, second week is 2001 + 1/52, third week > # is 2001 + 2/52, etc. > new.freq <- function(d, freq = 52) { + y <- as.Date(cut(range(d), "years")) + c(0, 367) + yd <- seq(y[1], y[2], "year") + yy <- as.numeric(format(yd, "%Y")) + floor(freq * approx(yd, yy, xout = d)$y) / freq + } > > # take last point in each period > aggregate(z, new.freq, tail, 1) 2001(1) 2001(2) 2001(3) 2001(4) 2001(5) 2001(6) 2001(7) 2001(8) 2.183643 2.164371 5.595281 5.329508 5.179532 7.487429 8.738325 9.575781 2001(9) 2001(10) 2001(11) 2001(12) 2001(13) 2001(14) 2001(15) 2001(16) 9.694612 12.511781 12.389843 12.378759 11.785300 16.124931 15.955066 16.983810 2001(17) 2001(18) 2001(19) 2001(20) 2001(21) 2001(22) 2001(23) 2001(24) 18.943836 19.821221 20.593901 21.918977 22.782136 23.074565 22.010648 25.619826 2001(25) 2001(26) 2001(27) 2001(28) 2001(29) 2001(30) 2001(31) 2001(32) 25.943871 26.844204 26.529248 28.521850 30.417942 32.358680 31.897212 33.387672 2001(33) 2001(34) 2001(35) 2001(36) 2001(37) 2001(38) 2001(39) 2001(40) 33.946195 33.622940 35.585005 36.605710 37.940687 40.100025 40.763176 40.835476 2001(41) 2001(42) 2001(43) 2001(44) 2001(45) 2001(46) 2001(47) 2001(48) 41.746638 43.696963 44.556663 44.311244 45.292505 47.364582 48.768533 48.887654 2001(49) 2001(50) 2001(51) 2001(52) 2002(1) 2002(2) 2002(3) 2002(4) 50.881108 51.398106 51.387974 53.341120 52.870637 56.433024 57.980400 56.632779 2002(5) 2002(6) 2002(7) 2002(8) 2002(9) 2002(10) 2002(11) 2002(12) 56.955865 59.569720 59.864945 63.401618 61.960760 63.689739 64.028002 64.256727 2002(13) 2002(14) 2002(15) 2002(16) 2002(17) 2002(18) 2002(19) 2002(20) 66.188792 65.195041 69.465555 69.153253 72.172612 71.475510 71.290054 73.610726 2002(21) 2002(22) 2002(23) 2002(24) 2002(25) 2002(26) 2002(27) 2002(28) 73.065902 73.746367 76.291446 76.556708 78.001105 79.074341 79.410479 80.431331 2002(29) 2002(30) 2002(31) 2002(32) 2002(33) 2002(34) 2002(35) 2002(36) 81.864821 84.178087 82.476433 85.593946 86.332950 88.063100 87.695816 89.370019 2002(37) 2002(38) 2002(39) 2002(40) 2002(41) 2002(42) 2002(43) 2002(44) 90.267099 90.457480 93.207868 94.160403 94.700214 96.586833 96.558486 95.723408 2002(45) 2002(46) 2002(47) 97.426735 97.775387 99.526599 > > # or, take mean of all points in each > aggregate(z, new.freq, mean) 2001(1) 2001(2) 2001(3) 2001(4) 2001(5) 2001(6) 2001(7) 2001(8) 1.278595 2.164371 5.595281 5.329508 5.179532 7.487429 8.738325 9.575781 2001(9) 2001(10) 2001(11) 2001(12) 2001(13) 2001(14) 2001(15) 2001(16) 9.694612 12.511781 12.389843 12.378759 11.785300 16.124931 15.955066 16.983810 2001(17) 2001(18) 2001(19) 2001(20) 2001(21) 2001(22) 2001(23) 2001(24) 18.943836 19.821221 20.593901 21.918977 22.782136 23.074565 22.010648 25.619826 2001(25) 2001(26) 2001(27) 2001(28) 2001(29) 2001(30) 2001(31) 2001(32) 25.943871 26.844204 26.529248 28.521850 30.417942 32.358680 31.897212 33.387672 2001(33) 2001(34) 2001(35) 2001(36) 2001(37) 2001(38) 2001(39) 2001(40) 33.946195 33.622940 35.585005 36.605710 37.940687 40.100025 40.763176 40.835476 2001(41) 2001(42) 2001(43) 2001(44) 2001(45) 2001(46) 2001(47) 2001(48) 41.746638 43.696963 44.556663 44.311244 45.292505 47.364582 48.768533 48.887654 2001(49) 2001(50) 2001(51) 2001(52) 2002(1) 2002(2) 2002(3) 2002(4) 50.881108 51.398106 51.387974 53.341120 52.870637 56.433024 57.980400 56.632779 2002(5) 2002(6) 2002(7) 2002(8) 2002(9) 2002(10) 2002(11) 2002(12) 56.955865 59.569720 59.864945 63.401618 61.960760 63.689739 64.028002 64.256727 2002(13) 2002(14) 2002(15) 2002(16) 2002(17) 2002(18) 2002(19) 2002(20) 66.188792 65.195041 69.465555 69.153253 72.172612 71.475510 71.290054 73.610726 2002(21) 2002(22) 2002(23) 2002(24) 2002(25) 2002(26) 2002(27) 2002(28) 73.065902 73.746367 76.291446 76.556708 78.001105 79.074341 79.410479 80.431331 2002(29) 2002(30) 2002(31) 2002(32) 2002(33) 2002(34) 2002(35) 2002(36) 81.864821 84.178087 82.476433 85.593946 86.332950 88.063100 87.695816 89.370019 2002(37) 2002(38) 2002(39) 2002(40) 2002(41) 2002(42) 2002(43) 2002(44) 90.267099 90.457480 93.207868 94.160403 94.700214 96.586833 96.558486 95.723408 2002(45) 2002(46) 2002(47) 97.426735 97.775387 99.526599 > > # example of taking means in the presence of NAs > z.na <- zooreg(c(1:364, NA), start = as.Date("2001-01-01")) > aggregate(z.na, as.yearqtr, mean, na.rm = TRUE) 2001 Q1 2001 Q2 2001 Q3 2001 Q4 45.5 136.0 227.5 319.0 > > # Find the sd of all days that lie in any Jan, all days that lie in > # any Feb, ..., all days that lie in any Dec (i.e. output is vector with > # 12 components) > aggregate(z, format(time(z), "%m"), sd) 01 02 03 04 05 06 07 08 27.931987 27.985392 27.679111 27.774779 27.328400 27.840695 27.520893 28.058606 09 10 11 12 27.806512 28.066187 27.406884 1.589453 > > > > > cleanEx() detaching ‘package:chron’ > nameEx("as.zoo") > ### * as.zoo > > flush(stderr()); flush(stdout()) > > ### Name: as.zoo > ### Title: Coercion from and to zoo > ### Aliases: as.zoo as.zoo.default as.zoo.data.frame as.zoo.fts as.zoo.its > ### as.zoo.irts as.zoo.matrix as.zoo.mcmc as.zoo.tis as.zoo.xts > ### as.zoo.zoo as.matrix.zoo as.vector.zoo as.data.frame.zoo as.list.zoo > ### as.list.ts as.zoo.ts as.ts.zoo > ### Keywords: ts > > ### ** Examples > > suppressWarnings(RNGversion("3.5.0")) > set.seed(1) > > ## coercion to zoo: > ## default method > as.zoo(rnorm(5)) 1 2 3 4 5 -0.6264538 0.1836433 -0.8356286 1.5952808 0.3295078 > ## method for "ts" objects > as.zoo(ts(rnorm(5), start = 1981, freq = 12)) Jan 1981 Feb 1981 Mar 1981 Apr 1981 May 1981 -0.8204684 0.4874291 0.7383247 0.5757814 -0.3053884 > > ## coercion from zoo: > x.date <- as.POSIXct(paste("2003-", rep(1:4, 4:1), "-", sample(1:28, 10, replace = TRUE), sep = "")) > x <- zoo(matrix(rnorm(24), ncol = 2), x.date) > as.matrix(x) x.1 x.2 2003-01-04 0.82122120 1.35867955 2003-01-06 -0.01619026 -0.47815006 2003-01-19 0.94383621 0.41794156 2003-01-27 -0.04493361 -1.47075238 2003-02-01 0.78213630 -0.05380504 2003-02-08 0.59390132 -0.10278773 2003-02-11 0.91897737 0.38767161 2003-03-11 0.07456498 -1.37705956 2003-03-25 -1.98935170 -0.41499456 2003-04-10 0.61982575 -0.39428995 > as.vector(x) [1] 0.82122120 -0.01619026 0.94383621 -0.04493361 0.78213630 0.59390132 [7] 0.91897737 0.07456498 -1.98935170 0.61982575 1.35867955 -0.47815006 [13] 0.41794156 -1.47075238 -0.05380504 -0.10278773 0.38767161 -1.37705956 [19] -0.41499456 -0.39428995 > as.data.frame(x) x.1 x.2 2003-01-04 0.82122120 1.35867955 2003-01-06 -0.01619026 -0.47815006 2003-01-19 0.94383621 0.41794156 2003-01-27 -0.04493361 -1.47075238 2003-02-01 0.78213630 -0.05380504 2003-02-08 0.59390132 -0.10278773 2003-02-11 0.91897737 0.38767161 2003-03-11 0.07456498 -1.37705956 2003-03-25 -1.98935170 -0.41499456 2003-04-10 0.61982575 -0.39428995 > as.list(x) $x.1 2003-01-04 2003-01-06 2003-01-19 2003-01-27 2003-02-01 2003-02-08 0.82122120 -0.01619026 0.94383621 -0.04493361 0.78213630 0.59390132 2003-02-11 2003-03-11 2003-03-25 2003-04-10 0.91897737 0.07456498 -1.98935170 0.61982575 $x.2 2003-01-04 2003-01-06 2003-01-19 2003-01-27 2003-02-01 2003-02-08 1.35867955 -0.47815006 0.41794156 -1.47075238 -0.05380504 -0.10278773 2003-02-11 2003-03-11 2003-03-25 2003-04-10 0.38767161 -1.37705956 -0.41499456 -0.39428995 > > > > cleanEx() > nameEx("coredata") > ### * coredata > > flush(stderr()); flush(stdout()) > > ### Name: coredata > ### Title: Extracting/Replacing the Core Data of Objects > ### Aliases: coredata coredata.default coredata.zoo coredata.ts > ### coredata.its coredata.irts coredata<- coredata<-.zoo coredata<-.ts > ### coredata<-.irts coredata<-.its > ### Keywords: ts > > ### ** Examples > > suppressWarnings(RNGversion("3.5.0")) > set.seed(1) > > x.date <- as.Date(paste(2003, rep(1:4, 4:1), seq(1,20,2), sep = "-")) > x <- zoo(matrix(rnorm(20), ncol = 2), x.date) > > ## the full time series > x 2003-01-01 -0.6264538 1.51178117 2003-01-03 0.1836433 0.38984324 2003-01-05 -0.8356286 -0.62124058 2003-01-07 1.5952808 -2.21469989 2003-02-09 0.3295078 1.12493092 2003-02-11 -0.8204684 -0.04493361 2003-02-13 0.4874291 -0.01619026 2003-03-15 0.7383247 0.94383621 2003-03-17 0.5757814 0.82122120 2003-04-19 -0.3053884 0.59390132 > ## and only matrix of observations > coredata(x) [,1] [,2] [1,] -0.6264538 1.51178117 [2,] 0.1836433 0.38984324 [3,] -0.8356286 -0.62124058 [4,] 1.5952808 -2.21469989 [5,] 0.3295078 1.12493092 [6,] -0.8204684 -0.04493361 [7,] 0.4874291 -0.01619026 [8,] 0.7383247 0.94383621 [9,] 0.5757814 0.82122120 [10,] -0.3053884 0.59390132 > > ## change the observations > coredata(x) <- matrix(1:20, ncol = 2) > x 2003-01-01 1 11 2003-01-03 2 12 2003-01-05 3 13 2003-01-07 4 14 2003-02-09 5 15 2003-02-11 6 16 2003-02-13 7 17 2003-03-15 8 18 2003-03-17 9 19 2003-04-19 10 20 > > > > cleanEx() > nameEx("frequency") > ### * frequency > > flush(stderr()); flush(stdout()) > > ### Name: frequency<- > ### Title: Replacing the Index of Objects > ### Aliases: frequency<- frequency<-.zoo frequency<-.zooreg > ### Keywords: ts > > ### ** Examples > > z <- zooreg(1:5) > z 1 2 3 4 5 1 2 3 4 5 > as.ts(z) Time Series: Start = 1 End = 5 Frequency = 1 [1] 1 2 3 4 5 > frequency(z) <- 3 > z 1(1) 2(1) 3(1) 4(1) 5(1) 1 2 3 4 5 > as.ts(z) Time Series: Start = c(1, 1) End = c(5, 1) Frequency = 3 [1] 1 NA NA 2 NA NA 3 NA NA 4 NA NA 5 > > > > cleanEx() > nameEx("ggplot2.zoo") > ### * ggplot2.zoo > > flush(stderr()); flush(stdout()) > > ### Name: ggplot2.zoo > ### Title: Convenience Functions for Plotting zoo Objects with ggplot2 > ### Aliases: autoplot.zoo fortify.zoo ggplot2.zoo facet_free yearmon_trans > ### yearqtr_trans scale_x_yearmon scale_y_yearmon scale_x_yearqtr > ### scale_y_yearqtr scale_type.yearmon scale_type.yearqtr > > ### ** Examples > > if(require("ggplot2") && require("scales")) { + suppressWarnings(RNGversion("3.5.0")) + set.seed(1) + + ## example data + x.Date <- as.Date(paste(2003, 02, c(1, 3, 7, 9, 14), sep = "-")) + x <- zoo(rnorm(5), x.Date) + xlow <- x - runif(5) + xhigh <- x + runif(5) + z <- cbind(x, xlow, xhigh) + + ## univariate plotting + autoplot(x) + ## by hand + ggplot(aes(x = Index, y = Value), data = fortify(x, melt = TRUE)) + + geom_line() + xlab("Index") + ylab("x") + ## adding series one at a time + last_plot() + geom_line(aes(x = Index, y = xlow), colour = "red", data = fortify(xlow)) + ## add ribbon for high/low band + ggplot(aes(x = Index, y = x, ymin = xlow, ymax = xhigh), data = fortify(x)) + + geom_ribbon(fill = "darkgray") + geom_line() + + ## multivariate plotting in multiple or single panels + autoplot(z) ## multiple without color/linetype + autoplot(z, facets = Series ~ .) ## multiple with series-dependent color/linetype + autoplot(z, facets = NULL) ## single with series-dependent color/linetype + ## by hand with color/linetype and with/without facets + ggz <- ggplot(aes(x = Index, y = Value, group = Series, colour = Series, linetype = Series), + data = fortify(z, melt = TRUE)) + geom_line() + xlab("Index") + ylab("") + ggz + ggz + facet_grid(Series ~ .) + ## variations + autoplot(z, geom = "point") + autoplot(z, facets = NULL) + geom_point() + autoplot(z, facets = NULL) + scale_colour_grey() + theme_bw() + + ## for "ts" series via coercion + autoplot(as.zoo(EuStockMarkets)) + autoplot(as.zoo(EuStockMarkets), facets = NULL) + + autoplot(z) + + aes(colour = NULL, linetype = NULL) + + facet_grid(Series ~ ., scales = "free_y") + + autoplot(z) + aes(colour = NULL, linetype = NULL) + facet_free() # same + + z.yq <- zooreg(rnorm(50), as.yearqtr("2000-1"), freq = 4) + autoplot(z.yq) + + ## mimic matplot + data <- cbind(A = c(6, 1, NA, NA), B = c(16, 4, 1, NA), C = c(25, 7, 2, 1)) + autoplot(zoo(data), facet = NULL) + geom_point() + ## with different line types + autoplot(zoo(data), facet = NULL) + geom_point() + aes(linetype = Series) + + ## illustrate just fortify() method + z <- zoo(data) + fortify(z) + fortify(z, melt = TRUE) + fortify(z, melt = TRUE, names = c("Time", NA, "Data")) + fortify(z, melt = TRUE, names = c(Index = "Time")) + + ## with/without splitting + z <- zoo(cbind(a.A = 1:2, a.B = 2:3, b.A = 3:4, c.B = 4:5)) + fortify(z) + fortify(z, melt = TRUE, sep = ".", names = list(Series = c("Lower", "Upper"))) + + ## scale_x_yearmon with custom discrete breaks + df <- data.frame(dates = as.yearmon("2018-08") + 0:6/12, values = c(2:6, 0, 1)) + ggdf <- ggplot(df, aes(x = dates, y = values)) + + geom_bar(position = "dodge", stat = "identity") + theme_light() + + xlab("Month") + ylab("Values") + ggdf ## with default scale_x_yearmon + ggdf + scale_x_yearmon(breaks = df$dates) ## with custom discrete breaks + } Loading required package: ggplot2 Loading required package: scales > > > > cleanEx() detaching ‘package:scales’, ‘package:ggplot2’ > nameEx("index") > ### * index > > flush(stderr()); flush(stdout()) > > ### Name: index > ### Title: Extracting/Replacing the Index of Objects > ### Aliases: index index.default index.zoo index.ts time.zoo index<- > ### index<-.zoo time<- time<-.zoo start.zoo end.zoo > ### Keywords: ts > > ### ** Examples > > suppressWarnings(RNGversion("3.5.0")) > set.seed(1) > > x.date <- as.Date(paste(2003, 2, c(1, 3, 7, 9, 14), sep = "-")) > x <- zoo(rnorm(5), x.date) > > ## query index/time of a zoo object > index(x) [1] "2003-02-01" "2003-02-03" "2003-02-07" "2003-02-09" "2003-02-14" > time(x) [1] "2003-02-01" "2003-02-03" "2003-02-07" "2003-02-09" "2003-02-14" > > ## change class of index from Date to POSIXct > ## relative to current time zone > x 2003-02-01 2003-02-03 2003-02-07 2003-02-09 2003-02-14 -0.6264538 0.1836433 -0.8356286 1.5952808 0.3295078 > index(x) <- as.POSIXct(format(time(x)),tz="") > x 2003-02-01 2003-02-03 2003-02-07 2003-02-09 2003-02-14 -0.6264538 0.1836433 -0.8356286 1.5952808 0.3295078 > > ## replace index/time of a zoo object > index(x) <- 1:5 > x 1 2 3 4 5 -0.6264538 0.1836433 -0.8356286 1.5952808 0.3295078 > time(x) <- 6:10 > x 6 7 8 9 10 -0.6264538 0.1836433 -0.8356286 1.5952808 0.3295078 > > ## query start and end of a zoo object > start(x) [1] 6 > end(x) [1] 10 > > ## query index of a usual matrix > xm <- matrix(rnorm(10), ncol = 2) > index(xm) [1] 1 2 3 4 5 > > > > cleanEx() > nameEx("is.regular") > ### * is.regular > > flush(stderr()); flush(stdout()) > > ### Name: is.regular > ### Title: Check Regularity of a Series > ### Aliases: is.regular is.regular.zoo is.regular.ts is.regular.zooreg > ### is.regular.default > ### Keywords: ts > > ### ** Examples > > ## checking of a strictly regular zoo series > z <- zoo(1:10, seq(2000, 2002.25, by = 0.25), frequency = 4) > z 2000 Q1 2000 Q2 2000 Q3 2000 Q4 2001 Q1 2001 Q2 2001 Q3 2001 Q4 2002 Q1 2002 Q2 1 2 3 4 5 6 7 8 9 10 > class(z) [1] "zooreg" "zoo" > frequency(z) ## extraction of frequency attribute [1] 4 > is.regular(z) [1] TRUE > is.regular(z, strict = TRUE) [1] TRUE > ## by omitting observations, the series is not strictly regular > is.regular(z[-3]) [1] TRUE > is.regular(z[-3], strict = TRUE) [1] FALSE > > ## checking of a plain zoo series without frequency attribute > ## which is in fact regular > z <- zoo(1:10, seq(2000, 2002.25, by = 0.25)) > z 2000 2000.25 2000.5 2000.75 2001 2001.25 2001.5 2001.75 2002 2002.25 1 2 3 4 5 6 7 8 9 10 > class(z) [1] "zoo" > frequency(z) ## data driven computation of frequency [1] 4 > is.regular(z) [1] TRUE > is.regular(z, strict = TRUE) [1] TRUE > ## by omitting observations, the series is not strictly regular > is.regular(z[-3]) [1] TRUE > is.regular(z[-3], strict = TRUE) [1] FALSE > > suppressWarnings(RNGversion("3.5.0")) > set.seed(1) > > ## checking of an irregular zoo series > z <- zoo(1:10, rnorm(10)) > z -0.8356 -0.8205 -0.6265 -0.3054 0.1836 0.3295 0.4874 0.5758 0.7383 1.5953 3 6 1 10 2 5 7 9 8 4 > class(z) [1] "zoo" > frequency(z) ## attempt of data-driven frequency computation NULL > is.regular(z) [1] FALSE > is.regular(z, strict = TRUE) [1] FALSE > > > > cleanEx() > nameEx("lag.zoo") > ### * lag.zoo > > flush(stderr()); flush(stdout()) > > ### Name: lag.zoo > ### Title: Lags and Differences of zoo Objects > ### Aliases: lag.zoo diff.zoo > ### Keywords: ts > > ### ** Examples > > x <- zoo(11:21) > > lag(x, k = 1) 1 2 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 21 > lag(x, k = -1) 2 3 4 5 6 7 8 9 10 11 11 12 13 14 15 16 17 18 19 20 > # this pairs each value of x with the next or future value > merge(x, lag1 = lag(x, k=1)) x lag1 1 11 12 2 12 13 3 13 14 4 14 15 5 15 16 6 16 17 7 17 18 8 18 19 9 19 20 10 20 21 11 21 NA > diff(x^3) 2 3 4 5 6 7 8 9 10 11 397 469 547 631 721 817 919 1027 1141 1261 > diff(x^3, -1) 1 2 3 4 5 6 7 8 9 10 397 469 547 631 721 817 919 1027 1141 1261 > diff(x^3, na.pad = TRUE) 1 2 3 4 5 6 7 8 9 10 11 NA 397 469 547 631 721 817 919 1027 1141 1261 > > > > > cleanEx() > nameEx("make.par.list") > ### * make.par.list > > flush(stderr()); flush(stdout()) > > ### Name: make.par.list > ### Title: Make a List from a Parameter Specification > ### Aliases: make.par.list > ### Keywords: ts > > ### ** Examples > > make.par.list(letters[1:5], 1:5, 3, 5) $a [1] 1 $b [1] 2 $c [1] 3 $d [1] 4 $e [1] 5 > suppressWarnings( make.par.list(letters[1:5], 1:4, 3, 5, 99) ) $a [1] 1 $b [1] 2 $c [1] 3 $d [1] 4 $e [1] 1 > make.par.list(letters[1:5], c(d=3), 3, 5, 99) $a [1] 99 $b [1] 99 $c [1] 99 $d [1] 3 $e [1] 99 > make.par.list(letters[1:5], list(d=1:2, 99), 3, 5) $a [1] 99 $b [1] 99 $c [1] 99 $d [1] 1 2 1 $e [1] 99 > make.par.list(letters[1:5], list(d=1:2, 99, 100), 3, 5) $a [1] 99 $b [1] 100 $c [1] 99 $d [1] 1 2 1 $e [1] 100 > > > > cleanEx() > nameEx("merge.zoo") > ### * merge.zoo > > flush(stderr()); flush(stdout()) > > ### Name: merge.zoo > ### Title: Merge Two or More zoo Objects > ### Aliases: merge.zoo rbind.zoo c.zoo cbind.zoo > ### Keywords: ts > > ### ** Examples > > ## simple merging > x.date <- as.Date(paste(2003, 02, c(1, 3, 7, 9, 14), sep = "-")) > x <- zoo(rnorm(5), x.date) > > y1 <- zoo(matrix(1:10, ncol = 2), 1:5) > y2 <- zoo(matrix(rnorm(10), ncol = 2), 3:7) > > ## using arguments `fill' and `suffixes' > merge(y1, y2, all = FALSE) y1.1 y1.2 y2.1 y2.2 3 3 8 -0.8204684 1.5117812 4 4 9 0.4874291 0.3898432 5 5 10 0.7383247 -0.6212406 > merge(y1, y2, all = FALSE, suffixes = c("a", "b")) a.1 a.2 b.1 b.2 3 3 8 -0.8204684 1.5117812 4 4 9 0.4874291 0.3898432 5 5 10 0.7383247 -0.6212406 > merge(y1, y2, all = TRUE) y1.1 y1.2 y2.1 y2.2 1 1 6 NA NA 2 2 7 NA NA 3 3 8 -0.8204684 1.5117812 4 4 9 0.4874291 0.3898432 5 5 10 0.7383247 -0.6212406 6 NA NA 0.5757814 -2.2146999 7 NA NA -0.3053884 1.1249309 > merge(y1, y2, all = TRUE, fill = 0) y1.1 y1.2 y2.1 y2.2 1 1 6 0.0000000 0.0000000 2 2 7 0.0000000 0.0000000 3 3 8 -0.8204684 1.5117812 4 4 9 0.4874291 0.3898432 5 5 10 0.7383247 -0.6212406 6 0 0 0.5757814 -2.2146999 7 0 0 -0.3053884 1.1249309 > > ## if different index classes are merged, as in > ## the next merge example then ## a warning is issued and > ### the indexes are coerced. > ## It is up to the user to ensure that the result makes sense. > merge(x, y1, y2, all = TRUE) Warning in merge.zoo(x, y1, y2, all = TRUE) : Index vectors are of different classes: Date integer integer x y1.1 y1.2 y2.1 y2.2 1970-01-02 NA 1 6 NA NA 1970-01-03 NA 2 7 NA NA 1970-01-04 NA 3 8 -0.8204684 1.5117812 1970-01-05 NA 4 9 0.4874291 0.3898432 1970-01-06 NA 5 10 0.7383247 -0.6212406 1970-01-07 NA NA NA 0.5757814 -2.2146999 1970-01-08 NA NA NA -0.3053884 1.1249309 2003-02-01 -0.6264538 NA NA NA NA 2003-02-03 0.1836433 NA NA NA NA 2003-02-07 -0.8356286 NA NA NA NA 2003-02-09 1.5952808 NA NA NA NA 2003-02-14 0.3295078 NA NA NA NA > > ## extend an irregular series to a regular one: > # create a constant series > z <- zoo(1, seq(4)[-2]) > # create a 0 dimensional zoo series > z0 <- zoo(, 1:4) > # do the extension > merge(z, z0) 1 2 3 4 1 NA 1 1 > # same but with zero fill > merge(z, z0, fill = 0) 1 2 3 4 1 0 1 1 > > merge(z, coredata(z), 1) z coredata(z) 1 1 1 1 1 3 1 1 1 4 1 1 1 > > > ## merge multiple series represented in a long form data frame > ## into a multivariate zoo series and plot, one series for each site. > ## Additional examples can be found here: > ## https://stat.ethz.ch/pipermail/r-help/2009-February/187094.html > ## https://stat.ethz.ch/pipermail/r-help/2009-February/187096.html > ## > m <- 5 # no of years > n <- 6 # no of sites > sites <- LETTERS[1:n] > suppressWarnings(RNGversion("3.5.0")) > set.seed(1) > DF <- data.frame(site = sites, year = 2000 + 1:m, data = rnorm(m*n)) > tozoo <- function(x) zoo(x$data, x$year) > Data <- do.call(merge, lapply(split(DF, DF$site), tozoo)) > plot(Data, screen = 1, col = 1:n, pch = 1:n, type = "o", xlab = "") > legend("bottomleft", legend = sites, lty = 1, pch = 1:n, col = 1:n) > > ## for each index value in x merge it with the closest index value in y > ## but retaining x's times. > x<-zoo(1:3,as.Date(c("1992-12-13", "1997-05-12", "1997-07-13"))) > y<-zoo(1:5,as.Date(c("1992-12-15", "1992-12-16", "1997-05-10","1997-05-19", "1997-07-13"))) > f <- function(u) which.min(abs(as.numeric(index(y)) - as.numeric(u))) > ix <- sapply(index(x), f) > cbind(x, y = coredata(y)[ix]) x y 1992-12-13 1 1 1997-05-12 2 3 1997-07-13 3 5 > > ## this merges each element of x with the closest time point in y at or > ## after x's time point (whereas in previous example it could be before > ## or after) > window(na.locf(merge(x, y), fromLast = TRUE), index(x)) x y 1992-12-13 1 1 1997-05-12 2 4 1997-07-13 3 5 > > > ## c() can combine several zoo series, e.g., zoo series with Date index > z <- zoo(1:5, as.Date("2000-01-01") + 0:4) > z2 <- zoo(6:7, time(z)[length(z)] + 1:2) > > ## c() combines these in a single series > c(z, z2) 2000-01-01 2000-01-02 2000-01-03 2000-01-04 2000-01-05 2000-01-06 2000-01-07 1 2 3 4 5 6 7 > > ## the order does not matter > c(z2, z) 2000-01-01 2000-01-02 2000-01-03 2000-01-04 2000-01-05 2000-01-06 2000-01-07 1 2 3 4 5 6 7 > > ## note, however, that combining a zoo series with an unclassed vector > ## of observations would try to coerce the indexes first > ## which might either give an unexpected result or an error in R >= 4.1.0 > ## c(z, 6:7) > > > > > cleanEx() > nameEx("na.StructTS") > ### * na.StructTS > > flush(stderr()); flush(stdout()) > > ### Name: na.StructTS > ### Title: Fill NA or specified positions. > ### Aliases: na.StructTS na.StructTS.zoo na.StructTS.ts > ### Keywords: ts > > ### ** Examples > > > z <- zooreg(rep(10 * seq(8), each = 4) + rep(c(3, 1, 2, 4), times = 8), + start = as.yearqtr(2000), freq = 4) > z[25] <- NA > > zout <- na.StructTS(z) > > plot(cbind(z, zout), screen = 1, col = 1:2, type = c("l", "p"), pch = 20) > > > > > > cleanEx() > nameEx("na.aggregate") > ### * na.aggregate > > flush(stderr()); flush(stdout()) > > ### Name: na.aggregate > ### Title: Replace NA by Aggregation > ### Aliases: na.aggregate na.aggregate.default > ### Keywords: ts > > ### ** Examples > > z <- zoo(c(1, NA, 3:9), + c(as.Date("2010-01-01") + 0:2, + as.Date("2010-02-01") + 0:2, + as.Date("2011-01-01") + 0:2)) > ## overall mean > na.aggregate(z) 2010-01-01 2010-01-02 2010-01-03 2010-02-01 2010-02-02 2010-02-03 2011-01-01 1.000 5.375 3.000 4.000 5.000 6.000 7.000 2011-01-02 2011-01-03 8.000 9.000 > ## group by months > na.aggregate(z, as.yearmon) 2010-01-01 2010-01-02 2010-01-03 2010-02-01 2010-02-02 2010-02-03 2011-01-01 1 2 3 4 5 6 7 2011-01-02 2011-01-03 8 9 > ## group by calendar months > na.aggregate(z, months) 2010-01-01 2010-01-02 2010-01-03 2010-02-01 2010-02-02 2010-02-03 2011-01-01 1.0 5.6 3.0 4.0 5.0 6.0 7.0 2011-01-02 2011-01-03 8.0 9.0 > ## group by years > na.aggregate(z, format, "%Y") 2010-01-01 2010-01-02 2010-01-03 2010-02-01 2010-02-02 2010-02-03 2011-01-01 1.0 3.8 3.0 4.0 5.0 6.0 7.0 2011-01-02 2011-01-03 8.0 9.0 > > > > cleanEx() > nameEx("na.approx") > ### * na.approx > > flush(stderr()); flush(stdout()) > > ### Name: na.approx > ### Title: Replace NA by Interpolation > ### Aliases: na.approx na.approx.zoo na.approx.zooreg na.approx.ts > ### na.approx.default na.spline na.spline.zoo na.spline.zooreg > ### na.spline.ts na.spline.default > ### Keywords: ts > > ### ** Examples > > > z <- zoo(c(2, NA, 1, 4, 5, 2), c(1, 3, 4, 6, 7, 8)) > > ## use underlying time scale for interpolation > na.approx(z) 1 3 4 6 7 8 2.000000 1.333333 1.000000 4.000000 5.000000 2.000000 > ## use equidistant spacing > na.approx(z, 1:6) 1 3 4 6 7 8 2.0 1.5 1.0 4.0 5.0 2.0 > > # with and without na.rm = FALSE > zz <- c(NA, 9, 3, NA, 3, 2) > na.approx(zz, na.rm = FALSE) [1] NA 9 3 3 3 2 > na.approx(zz) [1] 9 3 3 3 2 > > d0 <- as.Date("2000-01-01") > z <- zoo(c(11, NA, 13, NA, 15, NA), d0 + 1:6) > > # NA fill, drop or keep leading/trailing NAs > na.approx(z) 2000-01-02 2000-01-03 2000-01-04 2000-01-05 2000-01-06 11 12 13 14 15 > na.approx(z, na.rm = FALSE) 2000-01-02 2000-01-03 2000-01-04 2000-01-05 2000-01-06 2000-01-07 11 12 13 14 15 NA > > # extrapolate to point outside of range of time points > # (a) drop NA, (b) keep NA, (c) extrapolate using rule = 2 from approx() > na.approx(z, xout = d0 + 7) Data: numeric(0) Index: Date of length 0 > na.approx(z, xout = d0 + 7, na.rm = FALSE) 2000-01-08 NA > na.approx(z, xout = d0 + 7, rule = 2) 2000-01-08 15 > > # use splines - extrapolation handled differently > z <- zoo(c(11, NA, 13, NA, 15, NA), d0 + 1:6) > na.spline(z) 2000-01-02 2000-01-03 2000-01-04 2000-01-05 2000-01-06 2000-01-07 11 12 13 14 15 16 > na.spline(z, na.rm = FALSE) 2000-01-02 2000-01-03 2000-01-04 2000-01-05 2000-01-06 2000-01-07 11 12 13 14 15 16 > na.spline(z, xout = d0 + 1:6) 2000-01-02 2000-01-03 2000-01-04 2000-01-05 2000-01-06 2000-01-07 11 12 13 14 15 16 > na.spline(z, xout = d0 + 2:5) 2000-01-03 2000-01-04 2000-01-05 2000-01-06 12 13 14 15 > na.spline(z, xout = d0 + 7) 2000-01-08 17 > na.spline(z, xout = d0 + 7, na.rm = FALSE) 2000-01-08 17 > > ## using na.approx for disaggregation > zy <- zoo(1:3, 2000:2001) > > # yearly to monthly series > zmo <- na.approx(zy, xout = as.yearmon(2000+0:13/12)) > zmo Jan 2000 Feb 2000 Mar 2000 Apr 2000 May 2000 Jun 2000 Jul 2000 Aug 2000 1.000000 1.083333 1.166667 1.250000 1.333333 1.416667 1.500000 1.583333 Sep 2000 Oct 2000 Nov 2000 Dec 2000 Jan 2001 1.666667 1.750000 1.833333 1.916667 2.000000 > > # monthly to daily series > sq <- seq(as.Date(start(zmo)), as.Date(end(zmo), frac = 1), by = "day") > zd <- na.approx(zmo, x = as.Date, xout = sq) > head(zd) 2000-01-01 2000-01-02 2000-01-03 2000-01-04 2000-01-05 2000-01-06 1.000000 1.002688 1.005376 1.008065 1.010753 1.013441 > > # weekly to daily series > zww <- zoo(1:3, as.Date("2001-01-01") + seq(0, length = 3, by = 7)) > zww 2001-01-01 2001-01-08 2001-01-15 1 2 3 > zdd <- na.approx(zww, xout = seq(start(zww), end(zww), by = "day")) > zdd 2001-01-01 2001-01-02 2001-01-03 2001-01-04 2001-01-05 2001-01-06 2001-01-07 1.000000 1.142857 1.285714 1.428571 1.571429 1.714286 1.857143 2001-01-08 2001-01-09 2001-01-10 2001-01-11 2001-01-12 2001-01-13 2001-01-14 2.000000 2.142857 2.285714 2.428571 2.571429 2.714286 2.857143 2001-01-15 3.000000 > > # The lines do not show up because of the NAs > plot(cbind(z, z), type = "b", screen = 1) > # use na.approx to force lines to appear > plot(cbind(z, na.approx(z)), type = "b", screen = 1) > > # Workaround where less than 2 NAs can appear in a column > za <- zoo(cbind(1:5, NA, c(1:3, NA, 5), NA)); za 1 1 NA 1 NA 2 2 NA 2 NA 3 3 NA 3 NA 4 4 NA NA NA 5 5 NA 5 NA > > ix <- colSums(!is.na(za)) > 0 > za[, ix] <- na.approx(za[, ix]); za 1 1 NA 1 NA 2 2 NA 2 NA 3 3 NA 3 NA 4 4 NA 4 NA 5 5 NA 5 NA > > # using na.approx to create regularly spaced series > # z has points at 10, 20 and 40 minutes while output also has a point at 30 > if(require("chron")) { + tt <- as.chron("2000-01-01 10:00:00") + c(1, 2, 4) * as.numeric(times("00:10:00")) + z <- zoo(1:3, tt) + tseq <- seq(start(z), end(z), by = times("00:10:00")) + na.approx(z, xout = tseq) + } Loading required package: chron (01/01/00 10:10:00) (01/01/00 10:20:00) (01/01/00 10:30:00) 1.0 2.0 2.5 > > > > cleanEx() detaching ‘package:chron’ > nameEx("na.fill") > ### * na.fill > > flush(stderr()); flush(stdout()) > > ### Name: na.fill > ### Title: Fill NA or specified positions. > ### Aliases: na.fill na.fill0 na.fill.ts na.fill.zoo na.fill.default > ### Keywords: ts > > ### ** Examples > > > z <- zoo(c(NA, 2, NA, 1, 4, 5, 2, NA)) > na.fill(z, "extend") 1 2 3 4 5 6 7 8 2.0 2.0 1.5 1.0 4.0 5.0 2.0 2.0 > na.fill(z, c("extend", NA)) 1 2 3 4 5 6 7 8 2 2 NA 1 4 5 2 2 > na.fill(z, -(1:3)) 1 2 3 4 5 6 7 8 -1 2 -2 1 4 5 2 -3 > na.fill(z, list(NA, NULL, NA)) 1 2 4 5 6 7 8 NA 2 1 4 5 2 NA > > > > > cleanEx() > nameEx("na.locf") > ### * na.locf > > flush(stderr()); flush(stdout()) > > ### Name: na.locf > ### Title: Last Observation Carried Forward > ### Aliases: na.locf na.locf0 na.locf.data.frame na.locf.list > ### na.locf.default > ### Keywords: ts > > ### ** Examples > > az <- zoo(1:6) > > bz <- zoo(c(2,NA,1,4,5,2)) > na.locf(bz) 1 2 3 4 5 6 2 2 1 4 5 2 > na.locf(bz, fromLast = TRUE) 1 2 3 4 5 6 2 1 1 4 5 2 > > cz <- zoo(c(NA,9,3,2,3,2)) > na.locf(cz) 2 3 4 5 6 9 3 2 3 2 > > # generate and fill in missing dates > z <- zoo(c(0.007306621, 0.007659046, 0.007681013, + 0.007817548, 0.007847579, 0.007867313), + as.Date(c("1993-01-01", "1993-01-09", "1993-01-16", + "1993-01-23", "1993-01-30", "1993-02-06"))) > g <- seq(start(z), end(z), "day") > na.locf(z, xout = g) 1993-01-01 1993-01-02 1993-01-03 1993-01-04 1993-01-05 1993-01-06 0.007306621 0.007306621 0.007306621 0.007306621 0.007306621 0.007306621 1993-01-07 1993-01-08 1993-01-09 1993-01-10 1993-01-11 1993-01-12 0.007306621 0.007306621 0.007659046 0.007659046 0.007659046 0.007659046 1993-01-13 1993-01-14 1993-01-15 1993-01-16 1993-01-17 1993-01-18 0.007659046 0.007659046 0.007659046 0.007681013 0.007681013 0.007681013 1993-01-19 1993-01-20 1993-01-21 1993-01-22 1993-01-23 1993-01-24 0.007681013 0.007681013 0.007681013 0.007681013 0.007817548 0.007817548 1993-01-25 1993-01-26 1993-01-27 1993-01-28 1993-01-29 1993-01-30 0.007817548 0.007817548 0.007817548 0.007817548 0.007817548 0.007847579 1993-01-31 1993-02-01 1993-02-02 1993-02-03 1993-02-04 1993-02-05 0.007847579 0.007847579 0.007847579 0.007847579 0.007847579 0.007847579 1993-02-06 0.007867313 > > # similar but use a 2 second grid > > z <- zoo(1:9, as.POSIXct(c("2010-01-04 09:30:02", "2010-01-04 09:30:06", + "2010-01-04 09:30:07", "2010-01-04 09:30:08", "2010-01-04 09:30:09", + "2010-01-04 09:30:10", "2010-01-04 09:30:11", "2010-01-04 09:30:13", + "2010-01-04 09:30:14"))) > > g <- seq(start(z), end(z), by = "2 sec") > na.locf(z, xout = g) 2010-01-04 09:30:02 2010-01-04 09:30:04 2010-01-04 09:30:06 2010-01-04 09:30:08 1 1 2 4 2010-01-04 09:30:10 2010-01-04 09:30:12 2010-01-04 09:30:14 6 7 9 > > ## get 5th of every month or most recent date prior to 5th if 5th missing. > ## Result has index of the date actually used. > > z <- zoo(c(1311.56, 1309.04, 1295.5, 1296.6, 1286.57, 1288.12, + 1289.12, 1289.12, 1285.33, 1307.65, 1309.93, 1311.46, 1311.28, + 1308.11, 1301.74, 1305.41, 1309.72, 1310.61, 1305.19, 1313.21, + 1307.85, 1312.25, 1325.76), as.Date(c(13242, 13244, + 13245, 13248, 13249, 13250, 13251, 13252, 13255, 13256, 13257, + 13258, 13259, 13262, 13263, 13264, 13265, 13266, 13269, 13270, + 13271, 13272, 13274))) > > # z.na is same as z but with missing days added (with NAs) > # It is formed by merging z with a zero with series having all the dates. > > rng <- range(time(z)) > z.na <- merge(z, zoo(, seq(rng[1], rng[2], by = "day"))) > > # use na.locf to bring values forward picking off 5th of month > na.locf(z.na)[as.POSIXlt(time(z.na))$mday == 5] 2006-04-05 2006-05-05 1311.56 1312.25 > > ## this is the same as the last one except instead of always using the > ## 5th of month in the result we show the date actually used > > # idx has NAs wherever z.na does but has 1, 2, 3, ... instead of > # z.na's data values (so idx can be used for indexing) > > idx <- coredata(na.locf(seq_along(z.na) + (0 * z.na))) > > # pick off those elements of z.na that correspond to 5th > > z.na[idx[as.POSIXlt(time(z.na))$mday == 5]] 2006-04-04 2006-05-04 1311.56 1312.25 > > ## only fill single-day gaps > > merge(z.na, filled1 = na.locf(z.na, maxgap = 1)) z.na filled1 2006-04-04 1311.56 1311.56 2006-04-05 NA 1311.56 2006-04-06 1309.04 1309.04 2006-04-07 1295.50 1295.50 2006-04-08 NA NA 2006-04-09 NA NA 2006-04-10 1296.60 1296.60 2006-04-11 1286.57 1286.57 2006-04-12 1288.12 1288.12 2006-04-13 1289.12 1289.12 2006-04-14 1289.12 1289.12 2006-04-15 NA NA 2006-04-16 NA NA 2006-04-17 1285.33 1285.33 2006-04-18 1307.65 1307.65 2006-04-19 1309.93 1309.93 2006-04-20 1311.46 1311.46 2006-04-21 1311.28 1311.28 2006-04-22 NA NA 2006-04-23 NA NA 2006-04-24 1308.11 1308.11 2006-04-25 1301.74 1301.74 2006-04-26 1305.41 1305.41 2006-04-27 1309.72 1309.72 2006-04-28 1310.61 1310.61 2006-04-29 NA NA 2006-04-30 NA NA 2006-05-01 1305.19 1305.19 2006-05-02 1313.21 1313.21 2006-05-03 1307.85 1307.85 2006-05-04 1312.25 1312.25 2006-05-05 NA 1312.25 2006-05-06 1325.76 1325.76 > > ## fill NAs in first column by inflating the most recent non-NA > ## by the growth in second column. Note that elements of x-x > ## are NA if the corresponding element of x is NA and zero else > > m <- zoo(cbind(c(1, 2, NA, NA, 5, NA, NA), seq(7)^2), as.Date(1:7)) > > r <- na.locf(m[,1]) * m[,2] / na.locf(m[,2] + (m[,1]-m[,1])) > cbind(V1 = r, V2 = m[,2]) V1 V2 1970-01-02 1.0 1 1970-01-03 2.0 4 1970-01-04 4.5 9 1970-01-05 8.0 16 1970-01-06 5.0 25 1970-01-07 7.2 36 1970-01-08 9.8 49 > > ## repeat a quarterly value every month > ## preserving NAs > zq <- zoo(c(1, NA, 3, 4), as.yearqtr(2000) + 0:3/4) > tt <- as.yearmon(start(zq)) + seq(0, len = 3 * length(zq))/12 > na.locf(zq, xout = tt, maxgap = 0) Jan 2000 Feb 2000 Mar 2000 Apr 2000 May 2000 Jun 2000 Jul 2000 Aug 2000 1 1 1 NA NA NA 3 3 Sep 2000 Oct 2000 Nov 2000 Dec 2000 3 4 4 4 > > ## na.locf() can also be mimicked with ave() > x <- c(NA, 10, NA, NA, 20, NA) > f <- function(x) x[1] > ave(x, cumsum(!is.na(x)), FUN = f) [1] NA 10 10 10 20 20 > > ## by replacing f() with other functions various generalizations can be > ## obtained, e.g., > f <- function(x) if (length(x) > 3) x else x[1] # like maxgap > f <- function(x) replace(x, 1:min(length(x)), 3) # replace up to 2 NAs > f <- function(x) if (!is.na(x[1]) && x[1] > 0) x[1] else x # only positve numbers > > > > cleanEx() > nameEx("na.trim") > ### * na.trim > > flush(stderr()); flush(stdout()) > > ### Name: na.trim > ### Title: Trim Leading/Trailing Missing Observations > ### Aliases: na.trim na.trim.default na.trim.ts > ### Keywords: ts > > ### ** Examples > > # examples of na.trim > x <- zoo(c(1, 4, 6), c(2, 4, 6)) > xx <- zoo(matrix(c(1, 4, 6, NA, 5, 7), 3), c(2, 4, 6)) > na.trim(x) 2 4 6 1 4 6 > na.trim(xx) 4 4 5 6 6 7 > > # using na.trim for alignment > # cal defines the legal dates > # all dates within the date range of x should be present > cal <- zoo(,c(1, 2, 3, 6, 7)) > x <- zoo(c(12, 16), c(2, 6)) > na.trim(merge(x, cal)) 2 3 6 12 NA 16 > > > > > cleanEx() > nameEx("plot.zoo") > ### * plot.zoo > > flush(stderr()); flush(stdout()) > > ### Name: plot.zoo > ### Title: Plotting zoo Objects > ### Aliases: plot.zoo barplot.zoo boxplot.zoo lines.zoo points.zoo > ### Keywords: ts > > ### ** Examples > > ## example dates > x.Date <- as.Date(paste(2003, 02, c(1, 3, 7, 9, 14), sep = "-")) > > ## univariate plotting > x <- zoo(rnorm(5), x.Date) > x2 <- zoo(rnorm(5, sd = 0.2), x.Date) > plot(x) > lines(x2, col = 2) > > ## multivariate plotting > z <- cbind(x, x2, zoo(rnorm(5, sd = 0.5), x.Date)) > plot(z, type = "b", pch = 1:3, col = 1:3, ylab = list(expression(mu), "b", "c")) > colnames(z) <- LETTERS[1:3] > plot(z, screens = 1, col = list(B = 2)) > plot(z, type = "b", pch = 1:3, col = 1:3) > plot(z, type = "b", pch = list(A = 1:5, B = 3), col = list(C = 4, 2)) > plot(z, type = "b", screen = c(1,2,1), col = 1:3) > # right axis is for broken lines > plot(x) > opar <- par(usr = c(par("usr")[1:2], range(x2))) > lines(x2, lty = 2) > # axis(4) > axis(side = 4) > par(opar) > > > ## Custom x axis labelling using a custom panel. > # 1. test data > z <- zoo(c(21, 34, 33, 41, 39, 38, 37, 28, 33, 40), + as.Date(c("1992-01-10", "1992-01-17", "1992-01-24", "1992-01-31", + "1992-02-07", "1992-02-14", "1992-02-21", "1992-02-28", "1992-03-06", + "1992-03-13"))) > zz <- merge(a = z, b = z+10) > # 2. axis tick for every point. Also every 3rd point labelled. > my.panel <- function(x, y, ..., pf = parent.frame()) { + fmt <- "%b-%d" # format for axis labels + lines(x, y, ...) + # if bottom panel + if (with(pf, length(panel.number) == 0 || + panel.number %% nr == 0 || panel.number == nser)) { + # create ticks at x values and then label every third tick + axis(side = 1, at = x, labels = FALSE) + ix <- seq(1, length(x), 3) + labs <- format(x, fmt) + axis(side = 1, at = x[ix], labels = labs[ix], tcl = -0.7, cex.axis = 0.7) + } + } > # 3. plot > plot(zz, panel = my.panel, xaxt = "n") > > # with a single panel plot a fancy x-axis is just the same > # procedure as for the ordinary plot command > plot(zz, screen = 1, col = 1:2, xaxt = "n") > # axis(1, at = time(zz), labels = FALSE) > tt <- time(zz) > axis(side = 1, at = tt, labels = FALSE) > ix <- seq(1, length(tt), 3) > fmt <- "%b-%d" # format for axis labels > labs <- format(tt, fmt) > # axis(1, at = time(zz)[ix], labels = labs[ix], tcl = -0.7, cex.axis = 0.7) > axis(side = 1, at = tt[ix], labels = labs[ix], tcl = -0.7, cex.axis = 0.7) > legend("bottomright", colnames(zz), lty = 1, col = 1:2) > > ## plot a mulitple ts series with nice x-axis using panel function > tab <- ts(cbind(A = 1:24, B = 24:1), start = c(2006, 1), freq = 12) > pnl.xaxis <- function(...) { + lines(...) + panel.number <- parent.frame()$panel.number + nser <- parent.frame()$nser + # if bottom panel + if (!length(panel.number) || panel.number == nser) { + tt <- list(...)[[1]] + ym <- as.yearmon(tt) + mon <- as.numeric(format(ym, "%m")) + yy <- format(ym, "%y") + mm <- substring(month.abb[mon], 1, 1) + if (any(mon == 1)) + # axis(1, tt[mon == 1], yy[mon == 1], cex.axis = 0.7) + axis(side = 1, at = tt[mon == 1], labels = yy[mon == 1], cex.axis = 0.7) + # axis(1, tt[mon > 1], mm[mon > 1], cex.axis = 0.5, tcl = -0.3) + axis(side = 1, at = tt[mon > 1], labels = mm[mon > 1], cex.axis = 0.5, tcl = -0.3) + } + } > plot(as.zoo(tab), panel = pnl.xaxis, xaxt = "n", main = "Fancy X Axis") > > ## Another example with a custom axis > # test data > z <- zoo(matrix(1:25, 5), c(10,11,20,21)) > colnames(z) <- letters[1:5] > > plot(zoo(coredata(z)), xaxt = "n", panel = function(x, y, ..., Time = time(z)) { + lines(x, y, ...) + # if bottom panel + pf <- parent.frame() + if (with(pf, panel.number %% nr == 0 || panel.number == nser)) { + axis(side = 1, at = x, labels = Time) + } + }) > > > ## plot with left and right axes > ## modified from http://www.mayin.org/ajayshah/KB/R/html/g6.html > suppressWarnings(RNGversion("3.5.0")) > set.seed(1) > z <- zoo(cbind(A = cumsum(rnorm(100)), B = cumsum(rnorm(100, mean = 0.2)))) > opar <- par(mai = c(.8, .8, .2, .8)) > plot(z[,1], type = "l", + xlab = "x-axis label", ylab = colnames(z)[1]) > par(new = TRUE) > plot(z[,2], type = "l", ann = FALSE, yaxt = "n", col = "blue") > # axis(4) > axis(side = 4) > legend(x = "topleft", bty = "n", lty = c(1,1), col = c("black", "blue"), + legend = paste(colnames(z), c("(left scale)", "(right scale)"))) > usr <- par("usr") > # if you don't care about srt= in text then mtext is shorter: > # mtext(colnames(z)[2], 4, 2, col = "blue") > text(usr[2] + .1 * diff(usr[1:2]), mean(usr[3:4]), colnames(z)[2], + srt = -90, xpd = TRUE, col = "blue") > par(opar) > > > ## another plot with left and right axes > ## modified from https://stat.ethz.ch/pipermail/r-help/2014-May/375293.html > d1 <- c(38.2, 18.1, 83.2, 42.7, 22.8, 48.1, 81.8, 129.6, 52.0, 110.3) > d2 <- c(2.2, 0.8, 0.7, 1.6, 0.9, 0.9, 1.1, 2.8, 5.1, 2.1) > z1 <- zooreg(d1, start = as.POSIXct("2013-01-01 00:00:01"), frequency = 0.0000006) > z2 <- zooreg(d2, start = as.POSIXct("2013-01-01 00:00:20"), frequency = 0.0000006) > zt <- zooreg(rnorm(1050), start = as.POSIXct("2013-01-01 00:00:01"), frequency = 0.00007) > z <- merge(zt, z1, z2, all = TRUE) > z <- na.spline(z[,2:3], na.rm = FALSE) > ## function to round up to a number divisible by n (2011 by Owen Jones) > roundup <- function(x, n) ceiling(ceiling(x)/n) * n > ## plot how to match secondary y-axis ticks to primary ones > plot(z$z1, ylim = c(0, signif(max(na.omit(z$z1)), 2)), xlab = "") > ## use multiplication for even tick numbers and fake sekondary y-axis > max.yl <- roundup(max(na.omit(z$z2)), par("yaxp")[3]) > multipl.yl <- max(na.omit(z$z2)) / max.yl > multipl.z2 <- signif(max(na.omit(z$z1) * 1.05), 2)/max.yl > lines(z$z2 * multipl.z2, lty = 2) > at4 <- axTicks(4) > axis(4, at = at4, seq(0, max.yl, length.out = par("yaxp")[3] + 1)) > > > # automatically placed point labels > ## Not run: > ##D library("maptools") > ##D pointLabel(time(z), coredata(z[,2]), labels = format(time(z)), cex = 0.5) > ## End(Not run) > > ## plot one zoo series against the other. > plot(x, x2) > plot(x, x2, xy.labels = TRUE) > plot(x, x2, xy.labels = 1:5, xy.lines = FALSE) > > ## shade a portion of a plot and make axis fancier > > v <- zooreg(rnorm(50), start = as.yearmon(2004), freq = 12) > > plot(v, type = "n") > u <- par("usr") > rect(as.yearmon("2007-8"), u[3], as.yearmon("2009-11"), u[4], + border = 0, col = "grey") > lines(v) > axis(1, floor(time(v)), labels = FALSE, tcl = -1) > > ## shade certain times to show recessions, etc. > v <- zooreg(rnorm(50), start = as.yearmon(2004), freq = 12) > plot(v, type = "n") > u <- par("usr") > rect(as.yearmon("2007-8"), u[3], as.yearmon("2009-11"), u[4], + border = 0, col = "grey") > lines(v) > axis(1, floor(time(v)), labels = FALSE, tcl = -1) > > ## fill area under plot > > pnl.xyarea <- function(x, y, fill.base = 0, col = 1, ...) { + lines(x, y, ...) + panel.number <- parent.frame()$panel.number + col <- rep(col, length = panel.number)[panel.number] + polygon(c(x[1], x, tail(x, 1), x[1]), + c(fill.base, as.numeric(y), fill.base, fill.base), col = col) + } > plot(zoo(EuStockMarkets), col = rainbow(4), panel = pnl.xyarea) > > > ## barplot > x <- zoo(cbind(rpois(5, 2), rpois(5, 3)), x.Date) > barplot(x, beside = TRUE) > > ## boxplot > boxplot(x) > > ## 3d plot > ## The persp function in R (not part of zoo) works with zoo objects. > ## The following example is by Enrico Schumann. > ## https://stat.ethz.ch/pipermail/r-sig-finance/2009q1/003710.html > nC <- 10 # columns > nO <- 100 # observations > dataM <- array(runif(nC * nO), dim=c(nO, nC)) > zz <- zoo(dataM, 1:nO) > persp(1:nO, 1:nC, zz) > > # interactive plotting > ## Not run: > ##D library("TeachingDemos") > ##D tke.test1 <- list(Parameters = list( > ##D lwd = list("spinbox", init = 1, from = 0, to = 5, increment = 1, width = 5), > ##D lty = list("spinbox", init = 1, from = 0, to = 6, increment = 1, width = 5) > ##D )) > ##D z <- zoo(rnorm(25)) > ##D tkexamp(plot(z), tke.test1, plotloc = "top") > ## End(Not run) > > # setting ylim on a multi-panel plot - 2nd panel y axis range is 1-50 > data("anscombe", package = "datasets") > ans6 <- zoo(anscombe[, 1:6]) > screens <- c(1, 1, 2, 2, 3, 3) > ylim <- unname(tapply(as.list(ans6), screens, range)) > ylim[[2]] <- 1:50 # or ylim[[2]] <- c(1, 50) > plot(ans6, screens = screens, ylim = ylim) > > > > > graphics::par(get("par.postscript", pos = 'CheckExEnv')) > cleanEx() > nameEx("read.zoo") > ### * read.zoo > > flush(stderr()); flush(stdout()) > > ### Name: read.zoo > ### Title: Reading and Writing zoo Series > ### Aliases: read.zoo read.table.zoo read.csv.zoo read.csv2.zoo > ### read.delim.zoo read.delim2.zoo write.zoo > ### Keywords: ts > > ### ** Examples > > ## this manual page provides a few typical examples, many more cases > ## are covered in vignette("zoo-read", package = "zoo") > > ## read text lines with a single date column > Lines <- "2013-12-24 2 + 2013-12-25 3 + 2013-12-26 8" > read.zoo(text = Lines, FUN = as.Date) # explicit coercion 2013-12-24 2013-12-25 2013-12-26 2 3 8 > read.zoo(text = Lines, format = "%Y-%m-%d") # same 2013-12-24 2013-12-25 2013-12-26 2 3 8 > read.zoo(text = Lines) # same, via heuristic 2013-12-24 2013-12-25 2013-12-26 2 3 8 > > ## read text lines with date/time in separate columns > Lines <- "2013-11-24 12:41:21 2 + 2013-12-25 12:41:22.25 3 + 2013-12-26 12:41:22.75 8" > read.zoo(text = Lines, index = 1:2, + FUN = paste, FUN2 = as.POSIXct) # explicit coercion 2013-11-24 12:41:21 2013-12-25 12:41:22 2013-12-26 12:41:22 2 3 8 > read.zoo(text = Lines, index = 1:2, tz = "") # same 2013-11-24 12:41:21 2013-12-25 12:41:22 2013-12-26 12:41:22 2 3 8 > read.zoo(text = Lines, index = 1:2) # same, via heuristic 2013-11-24 12:41:21 2013-12-25 12:41:22 2013-12-26 12:41:22 2 3 8 > > ## read text lines with month/year in separate columns > Lines <- "Jan 1998 4.36 + Feb 1998 4.34" > read.zoo(text = Lines, index = 1:2, FUN = paste, FUN2 = as.yearmon) Jan 1998 Feb 1998 4.36 4.34 > > ## read directly from a data.frame (artificial and built-in BOD) > dat <- data.frame(date = paste("2000-01-", 10:15, sep = ""), + a = sin(1:6), b = cos(1:6)) > read.zoo(dat) a b 2000-01-10 0.8414710 0.5403023 2000-01-11 0.9092974 -0.4161468 2000-01-12 0.1411200 -0.9899925 2000-01-13 -0.7568025 -0.6536436 2000-01-14 -0.9589243 0.2836622 2000-01-15 -0.2794155 0.9601703 > data("BOD", package = "datasets") > read.zoo(BOD) 1 2 3 4 5 7 8.3 10.3 19.0 16.0 15.6 19.8 > > ## Not run: > ##D ## descriptions of typical examples > ##D > ##D ## turn *numeric* first column into yearmon index > ##D ## where number is year + fraction of year represented by month > ##D z <- read.zoo("foo.csv", sep = ",", FUN = as.yearmon) > ##D > ##D ## first column is of form yyyy.mm > ##D ## (Here we use format in place of as.character so that final zero > ##D ## is not dropped in dates like 2001.10 which as.character would do.) > ##D f <- function(x) as.yearmon(format(x, nsmall = 2), "%Y.%m") > ##D z <- read.zoo("foo.csv", header = TRUE, FUN = f) > ##D > ##D ## turn *character* first column into "Date" index > ##D ## Assume lines look like: 12/22/2007 1 2 > ##D z <- read.zoo("foo.tab", format = "%m/%d/%Y") > ##D > ##D # Suppose lines look like: 09112007 1 2 and there is no header > ##D z <- read.zoo("foo.txt", format = "%d%m%Y") > ##D > ##D ## csv file with first column of form YYYY-mm-dd HH:MM:SS > ##D ## Read in times as "chron" class. Requires chron 2.3-22 or later. > ##D z <- read.zoo("foo.csv", header = TRUE, sep = ",", FUN = as.chron) > ##D > ##D ## same but with custom format. Note as.chron uses POSIXt-style ##D > ##D ## Read in times as "chron" class. Requires chron 2.3-24 or later. > ##D z <- read.zoo("foo.csv", header = TRUE, sep = ",", FUN = as.chron, > ##D format = "##D > ##D > ##D ## same file format but read it in times as "POSIXct" class. > ##D z <- read.zoo("foo.csv", header = TRUE, sep = ",", tz = "") > ##D > ##D ## csv file with first column mm-dd-yyyy. Read times as "Date" class. > ##D z <- read.zoo("foo.csv", header = TRUE, sep = ",", format = "%m-%d-%Y") > ##D > ##D ## whitespace separated file with first column of form YYYY-mm-ddTHH:MM:SS > ##D ## and no headers. T appears literally. Requires chron 2.3-22 or later. > ##D z <- read.zoo("foo.csv", FUN = as.chron) > ##D > ##D # read in all csv files in the current directory and merge them > ##D read.zoo(Sys.glob("*.csv"), header = TRUE, sep = ",") > ##D > ##D # We use "NULL" in colClasses for those columns we don't need but in > ##D # col.names we still have to include dummy names for them. Of what > ##D # is left the index is the first three columns (1:3) which we convert > ##D # to chron class times in FUN and then truncate to 5 seconds in FUN2. > ##D # Finally we use aggregate = mean to average over the 5 second intervals. > ##D library("chron") > ##D > ##D Lines <- "CVX 20070201 9 30 51 73.25 81400 0 > ##D CVX 20070201 9 30 51 73.25 100 0 > ##D CVX 20070201 9 30 51 73.25 100 0 > ##D CVX 20070201 9 30 51 73.25 300 0 > ##D CVX 20070201 9 30 51 73.25 81400 0 > ##D CVX 20070201 9 40 51 73.25 100 0 > ##D CVX 20070201 9 40 52 73.25 100 0 > ##D CVX 20070201 9 40 53 73.25 300 0" > ##D > ##D z <- read.zoo(text = Lines, > ##D colClasses = c("NULL", "NULL", "numeric", "numeric", "numeric", > ##D "numeric", "numeric", "NULL"), > ##D col.names = c("Symbol", "Date", "Hour", "Minute", "Second", "Price", "Volume", "junk"), > ##D index = 1:3, # do not count columns that are "NULL" in colClasses > ##D FUN = function(h, m, s) times(paste(h, m, s, sep = ":")), > ##D FUN2 = function(tt) trunc(tt, "00:00:05"), > ##D aggregate = mean) > ## End(Not run) > > > > > cleanEx() > nameEx("rollapply") > ### * rollapply > > flush(stderr()); flush(stdout()) > > ### Name: rollapply > ### Title: Apply Rolling Functions > ### Aliases: rollapply rollapplyr rollapply.default rollapply.ts > ### rollapply.zoo > ### Keywords: iteration array ts > > ### ** Examples > > suppressWarnings(RNGversion("3.5.0")) > set.seed(1) > > ## rolling mean > z <- zoo(11:15, as.Date(31:35)) > rollapply(z, 2, mean) 1970-02-01 1970-02-02 1970-02-03 1970-02-04 11.5 12.5 13.5 14.5 > > ## non-overlapping means > z2 <- zoo(rnorm(6)) > rollapply(z2, 3, mean, by = 3) # means of nonoverlapping groups of 3 2 5 -0.4261464 0.3681067 > aggregate(z2, c(3,3,3,6,6,6), mean) # same 3 6 -0.4261464 0.3681067 > > ## optimized vs. customized versions > rollapply(z2, 3, mean) # uses rollmean which is optimized for mean 2 3 4 5 -0.4261464 0.3144318 0.3630533 0.3681067 > rollmean(z2, 3) # same 2 3 4 5 -0.4261464 0.3144318 0.3630533 0.3681067 > rollapply(z2, 3, (mean)) # does not use rollmean 2 3 4 5 -0.4261464 0.3144318 0.3630533 0.3681067 > > > ## rolling regression: > ## set up multivariate zoo series with > ## number of UK driver deaths and lags 1 and 12 > seat <- as.zoo(log(UKDriverDeaths)) > time(seat) <- as.yearmon(time(seat)) > seat <- merge(y = seat, y1 = lag(seat, k = -1), + y12 = lag(seat, k = -12), all = FALSE) > > ## run a rolling regression with a 3-year time window > ## (similar to a SARIMA(1,0,0)(1,0,0)_12 fitted by OLS) > rr <- rollapply(seat, width = 36, + FUN = function(z) coef(lm(y ~ y1 + y12, data = as.data.frame(z))), + by.column = FALSE, align = "right") > > ## plot the changes in coefficients > ## showing the shifts after the oil crisis in Oct 1973 > ## and after the seatbelt legislation change in Jan 1983 > plot(rr) > > > ## rolling mean by time window (e.g., 3 days) rather than > ## by number of observations (e.g., when these are unequally spaced): > # > ## - test data > tt <- as.Date("2000-01-01") + c(1, 2, 5, 6, 7, 8, 10) > z <- zoo(seq_along(tt), tt) > ## - fill it out to a daily series, zm, using NAs > ## using a zero width zoo series g on a grid > g <- zoo(, seq(start(z), end(z), "day")) > zm <- merge(z, g) > ## - 3-day rolling mean > rollapply(zm, 3, mean, na.rm = TRUE, fill = NA) 2000-01-02 2000-01-03 2000-01-04 2000-01-05 2000-01-06 2000-01-07 2000-01-08 NA 1.5 2.0 3.0 3.5 4.0 5.0 2000-01-09 2000-01-10 2000-01-11 5.5 6.5 NA > ## > ## - without expansion to regular grid: find interval widths > ## that encompass the previous 3 days for each Date > w <- seq_along(tt) - findInterval(tt - 3, tt) > ## a solution to computing the widths 'w' that is easier to read but slower > ## w <- sapply(tt, function(x) sum(tt >= x - 2 & tt <= x)) > ## > ## - rolling sum from 3-day windows > ## without vs. with expansion to regular grid > rollapplyr(z, w, sum) 2000-01-02 2000-01-03 2000-01-06 2000-01-07 2000-01-08 2000-01-09 2000-01-11 1 3 3 7 12 15 13 > rollapplyr(zm, 3, sum, partial = TRUE, na.rm = TRUE) 2000-01-02 2000-01-03 2000-01-04 2000-01-05 2000-01-06 2000-01-07 2000-01-08 1 3 3 2 3 7 12 2000-01-09 2000-01-10 2000-01-11 15 11 13 > > > ## rolling weekly sums (with some missing dates) > z <- zoo(1:11, as.Date("2016-03-09") + c(0:7, 9:10, 12)) > weeksum <- function(z) sum(z[time(z) > max(time(z)) - 7]) > zs <- rollapplyr(z, 7, weeksum, fill = NA, coredata = FALSE) > merge(value = z, weeksum = zs) value weeksum 2016-03-09 1 NA 2016-03-10 2 NA 2016-03-11 3 NA 2016-03-12 4 NA 2016-03-13 5 NA 2016-03-14 6 NA 2016-03-15 7 28 2016-03-16 8 35 2016-03-18 9 39 2016-03-19 10 45 2016-03-21 11 45 > > > ## replicate cumsum with either 'partial' or vector width 'k' > cumsum(1:10) [1] 1 3 6 10 15 21 28 36 45 55 > rollapplyr(1:10, 10, sum, partial = TRUE) [1] 1 3 6 10 15 21 28 36 45 55 > rollapplyr(1:10, 1:10, sum) [1] 1 3 6 10 15 21 28 36 45 55 > > > ## different values of rule argument > z <- zoo(c(NA, NA, 2, 3, 4, 5, NA)) > rollapply(z, 3, sum, na.rm = TRUE) 2 3 4 5 6 2 5 9 12 9 > rollapply(z, 3, sum, na.rm = TRUE, fill = NULL) 2 3 4 5 6 2 5 9 12 9 > rollapply(z, 3, sum, na.rm = TRUE, fill = NA) 1 2 3 4 5 6 7 NA 2 5 9 12 9 NA > rollapply(z, 3, sum, na.rm = TRUE, partial = TRUE) 1 2 3 4 5 6 7 0 2 5 9 12 9 5 > > # this will exclude time points 1 and 2 > # It corresponds to align = "right", width = 3 > rollapply(zoo(1:8), list(seq(-2, 0)), sum) 3 4 5 6 7 8 6 9 12 15 18 21 > > # but this will include points 1 and 2 > rollapply(zoo(1:8), list(seq(-2, 0)), sum, partial = 1) 1 2 3 4 5 6 7 8 1 3 6 9 12 15 18 21 > rollapply(zoo(1:8), list(seq(-2, 0)), sum, partial = 0) 1 2 3 4 5 6 7 8 1 3 6 9 12 15 18 21 > > # so will this > rollapply(zoo(1:8), list(seq(-2, 0)), sum, fill = NA) 1 2 3 4 5 6 7 8 NA NA 6 9 12 15 18 21 > > # by = 3, align = "right" > L <- rep(list(NULL), 8) > L[seq(3, 8, 3)] <- list(seq(-2, 0)) > str(L) List of 8 $ : NULL $ : NULL $ : int [1:3] -2 -1 0 $ : NULL $ : NULL $ : int [1:3] -2 -1 0 $ : NULL $ : NULL > rollapply(zoo(1:8), L, sum) 3 6 6 15 > > rollapply(zoo(1:8), list(0:2), sum, fill = 1:3) 1 2 3 4 5 6 7 8 6 9 12 15 18 21 3 3 > rollapply(zoo(1:8), list(0:2), sum, fill = 3) 1 2 3 4 5 6 7 8 6 9 12 15 18 21 3 3 > > L2 <- rep(list(-(2:0)), 10) > L2[5] <- list(NULL) > str(L2) List of 10 $ : int [1:3] -2 -1 0 $ : int [1:3] -2 -1 0 $ : int [1:3] -2 -1 0 $ : int [1:3] -2 -1 0 $ : NULL $ : int [1:3] -2 -1 0 $ : int [1:3] -2 -1 0 $ : int [1:3] -2 -1 0 $ : int [1:3] -2 -1 0 $ : int [1:3] -2 -1 0 > rollapply(zoo(1:10), L2, sum, fill = "extend") 1 2 3 4 5 6 7 8 9 10 6 6 6 9 12 15 18 21 24 27 > rollapply(zoo(1:10), L2, sum, fill = list("extend", NULL)) 1 2 3 4 6 7 8 9 10 6 6 6 9 15 18 21 24 27 > > rollapply(zoo(1:10), L2, sum, fill = list("extend", NA)) 1 2 3 4 5 6 7 8 9 10 6 6 6 9 NA 15 18 21 24 27 > > rollapply(zoo(1:10), L2, sum, fill = NA) 1 2 3 4 5 6 7 8 9 10 NA NA 6 9 NA 15 18 21 24 27 > rollapply(zoo(1:10), L2, sum, fill = 1:3) 1 2 3 4 5 6 7 8 9 10 1 1 6 9 2 15 18 21 24 27 > rollapply(zoo(1:10), L2, sum, partial = TRUE) 1 2 3 4 6 7 8 9 10 1 3 6 9 15 18 21 24 27 > rollapply(zoo(1:10), L2, sum, partial = TRUE, fill = 99) 1 2 3 4 5 6 7 8 9 10 1 3 6 9 99 15 18 21 24 27 > > rollapply(zoo(1:10), list(-1), sum, partial = 0) 1 2 3 4 5 6 7 8 9 10 0 1 2 3 4 5 6 7 8 9 > rollapply(zoo(1:10), list(-1), sum, partial = TRUE) 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 > > rollapply(zoo(cbind(a = 1:6, b = 11:16)), 3, rowSums, by.column = FALSE) 2 12 14 16 3 14 16 18 4 16 18 20 5 18 20 22 > > # these two are the same > rollapply(zoo(cbind(a = 1:6, b = 11:16)), 3, sum) a b 2 6 36 3 9 39 4 12 42 5 15 45 > rollapply(zoo(cbind(a = 1:6, b = 11:16)), 3, colSums, by.column = FALSE) a b 2 6 36 3 9 39 4 12 42 5 15 45 > > # these two are the same > rollapply(zoo(1:6), 2, sum, by = 2, align = "right") 2 4 6 3 7 11 > aggregate(zoo(1:6), c(2, 2, 4, 4, 6, 6), sum) 2 4 6 3 7 11 > > # these two are the same > rollapply(zoo(1:3), list(-1), c) 2 3 1 2 > lag(zoo(1:3), -1) 2 3 1 2 > > # these two are the same > rollapply(zoo(1:3), list(1), c) 1 2 2 3 > lag(zoo(1:3)) 1 2 2 3 > > # these two are the same > rollapply(zoo(1:5), list(c(-1, 0, 1)), sum) 2 3 4 6 9 12 > rollapply(zoo(1:5), 3, sum) 2 3 4 6 9 12 > > # these two are the same > rollapply(zoo(1:5), list(0:2), sum) 1 2 3 6 9 12 > rollapply(zoo(1:5), 3, sum, align = "left") 1 2 3 6 9 12 > > # these two are the same > rollapply(zoo(1:5), list(-(2:0)), sum) 3 4 5 6 9 12 > rollapply(zoo(1:5), 3, sum, align = "right") 3 4 5 6 9 12 > > # these two are the same > rollapply(zoo(1:6), list(NULL, NULL, -(2:0)), sum) 3 6 6 15 > rollapply(zoo(1:6), 3, sum, by = 3, align = "right") 3 6 6 15 > > # these two are the same > rollapply(zoo(1:5), list(c(-1, 1)), sum) 2 3 4 4 6 8 > rollapply(zoo(1:5), 3, function(x) sum(x[-2])) 2 3 4 4 6 8 > > # these two are the same > rollapply(1:5, 3, rev) [,1] [,2] [,3] [1,] 3 2 1 [2,] 4 3 2 [3,] 5 4 3 > embed(1:5, 3) [,1] [,2] [,3] [1,] 3 2 1 [2,] 4 3 2 [3,] 5 4 3 > > # these four are the same > x <- 1:6 > rollapply(c(0, 0, x), 3, sum, align = "right") - x [1] 0 1 3 5 7 9 > rollapply(x, 3, sum, partial = TRUE, align = "right") - x [1] 0 1 3 5 7 9 > rollapply(x, 3, function(x) sum(x[-3]), partial = TRUE, align = "right") [1] 1 3 3 5 7 9 > rollapply(x, list(-(2:1)), sum, partial = 0) [1] 0 1 3 5 7 9 > > # same as Matlab's buffer(x, n, p) for valid non-negative p > # See http://www.mathworks.com/help/toolbox/signal/buffer.html > x <- 1:30; n <- 7; p <- 3 > t(rollapply(c(rep(0, p), x, rep(0, n-p)), n, by = n-p, c)) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [1,] 0 2 6 10 14 18 22 26 [2,] 0 3 7 11 15 19 23 27 [3,] 0 4 8 12 16 20 24 28 [4,] 1 5 9 13 17 21 25 29 [5,] 2 6 10 14 18 22 26 30 [6,] 3 7 11 15 19 23 27 0 [7,] 4 8 12 16 20 24 28 0 > > # these three are the same > y <- 10 * seq(8); k <- 4; d <- 2 > # 1 > # from http://ucfagls.wordpress.com/2011/06/14/embedding-a-time-series-with-time-delay-in-r-part-ii/ > Embed <- function(x, m, d = 1, indices = FALSE, as.embed = TRUE) { + n <- length(x) - (m-1)*d + X <- seq_along(x) + if(n <= 0) + stop("Insufficient observations for the requested embedding") + out <- matrix(rep(X[seq_len(n)], m), ncol = m) + out[,-1] <- out[,-1, drop = FALSE] + + rep(seq_len(m - 1) * d, each = nrow(out)) + if(as.embed) + out <- out[, rev(seq_len(ncol(out)))] + if(!indices) + out <- matrix(x[out], ncol = m) + out + } > Embed(y, k, d) [,1] [,2] [,3] [,4] [1,] 70 50 30 10 [2,] 80 60 40 20 > # 2 > rollapply(y, list(-d * seq(0, k-1)), c) [,1] [,2] [,3] [,4] [1,] 70 50 30 10 [2,] 80 60 40 20 > # 3 > rollapply(y, d*k-1, function(x) x[d * seq(k-1, 0) + 1]) [,1] [,2] [,3] [,4] [1,] 70 50 30 10 [2,] 80 60 40 20 > > > ## mimic convolve() using rollapplyr() > A <- 1:4 > B <- 5:8 > ## convolve(..., type = "open") > cross <- function(x) x > rollapplyr(c(A, 0*B[-1]), length(B), cross, partial = TRUE) Warning in rbind(1, c(1, 2), c(1, 2, 3), c(1, 2, 3, 4), c(2, 3, 4, 0), c(3, : number of columns of result is not a multiple of vector length (arg 3) [,1] [,2] [,3] [,4] [1,] 1 1 1 1 [2,] 1 2 1 2 [3,] 1 2 3 1 [4,] 1 2 3 4 [5,] 2 3 4 0 [6,] 3 4 0 0 [7,] 4 0 0 0 > convolve(A, B, type = "open") [1] 8 23 44 70 56 39 20 > > # convolve(..., type = "filter") > rollapplyr(A, length(B), cross) [,1] [,2] [,3] [,4] [1,] 1 2 3 4 > convolve(A, B, type = "filter") [1] 70 > > > # weighted sum including partials near ends, keeping > ## alignment with wts correct > points <- zoo(cbind(lon = c(11.8300715, 11.8296697, + 11.8268708, 11.8267236, 11.8249612, 11.8251062), + lat = c(48.1099048, 48.10884, 48.1067431, 48.1066077, + 48.1037673, 48.103318), + dist = c(46.8463805878941, 33.4921440879536, 10.6101735030534, + 18.6085009578724, 6.97253109610173, 9.8912817449265))) > mysmooth <- function(z, wts = c(0.3, 0.4, 0.3)) { + notna <- !is.na(z) + sum(z[notna] * wts[notna]) / sum(wts[notna]) + } > points2 <- points > points2[, 1:2] <- rollapply(rbind(NA, coredata(points)[, 1:2], NA), 3, mysmooth) > points2 lon lat dist 1 11.82990 48.10945 46.846381 2 11.82895 48.10853 33.492144 3 11.82767 48.10733 10.610174 4 11.82624 48.10580 18.608501 5 11.82553 48.10448 6.972531 6 11.82504 48.10351 9.891282 > > > > cleanEx() > nameEx("rollmean") > ### * rollmean > > flush(stderr()); flush(stdout()) > > ### Name: rollmean > ### Title: Rolling Means/Maximums/Medians/Sums > ### Aliases: rollmean rollmax rollmedian rollsum rollmeanr rollmaxr > ### rollmedianr rollsumr rollmean.zoo rollmax.zoo rollmedian.zoo > ### rollsum.zoo rollmean.ts rollmax.ts rollmedian.ts rollsum.ts > ### rollmean.default rollmax.default rollmedian.default rollsum.default > ### Keywords: ts > > ### ** Examples > > suppressWarnings(RNGversion("3.5.0")) > set.seed(1) > > x.Date <- as.Date(paste(2004, rep(1:4, 4:1), sample(1:28, 10), sep = "-")) > x <- zoo(rnorm(12), x.Date) > > ## rolling operations for univariate series > rollmean(x, 3) 2004-01-11 2004-01-15 2004-01-23 2004-02-05 2004-02-21 2004-02-25 2004-03-13 0.1350951 0.6005117 0.3362392 0.5940580 0.5320787 -0.1043585 -0.8153657 2004-03-14 -0.5703365 > rollmax(x, 3) 2004-01-11 2004-01-15 2004-01-23 2004-02-05 2004-02-21 2004-02-25 2004-03-13 0.7383247 0.7383247 0.7383247 1.5117812 1.5117812 1.5117812 0.3898432 2004-03-14 1.1249309 > rollmedian(x, 3) 2004-01-11 2004-01-15 2004-01-23 2004-02-05 2004-02-21 2004-02-25 2004-03-13 0.4874291 0.5757814 0.5757814 0.5757814 0.3898432 0.3898432 -0.6212406 2004-03-14 -0.6212406 > rollsum(x, 3) 2004-01-11 2004-01-15 2004-01-23 2004-02-05 2004-02-21 2004-02-25 2004-03-13 0.4052854 1.8015351 1.0087177 1.7821741 1.5962360 -0.3130755 -2.4460972 2004-03-14 -1.7110095 > > ## rolling operations for multivariate series > xm <- zoo(matrix(1:12, 4, 3), x.Date[1:4]) > rollmean(xm, 3) 2004-01-11 2 6 10 2004-01-15 3 7 11 > rollmax(xm, 3) 2004-01-11 3 7 11 2004-01-15 4 8 12 > rollmedian(xm, 3) 2004-01-11 2 6 10 2004-01-15 3 7 11 > rollsum(xm, 3) 2004-01-11 6 18 30 2004-01-15 9 21 33 > > ## rollapply vs. dedicated rollmean > rollapply(xm, 3, mean) # uses rollmean 2004-01-11 2 6 10 2004-01-15 3 7 11 > rollapply(xm, 3, function(x) mean(x)) # does not use rollmean 2004-01-11 2 6 10 2004-01-15 3 7 11 > > > > cleanEx() > nameEx("window.zoo") > ### * window.zoo > > flush(stderr()); flush(stdout()) > > ### Name: window.zoo > ### Title: Extract/Replacing the Time Windows of Objects > ### Aliases: window.zoo window<-.zoo > ### Keywords: ts > > ### ** Examples > > suppressWarnings(RNGversion("3.5.0")) > set.seed(1) > > ## zoo example > x.date <- as.Date(paste(2003, rep(1:4, 4:1), seq(1,19,2), sep = "-")) > x <- zoo(matrix(rnorm(20), ncol = 2), x.date) > x 2003-01-01 -0.6264538 1.51178117 2003-01-03 0.1836433 0.38984324 2003-01-05 -0.8356286 -0.62124058 2003-01-07 1.5952808 -2.21469989 2003-02-09 0.3295078 1.12493092 2003-02-11 -0.8204684 -0.04493361 2003-02-13 0.4874291 -0.01619026 2003-03-15 0.7383247 0.94383621 2003-03-17 0.5757814 0.82122120 2003-04-19 -0.3053884 0.59390132 > > window(x, start = as.Date("2003-02-01"), end = as.Date("2003-03-01")) 2003-02-09 0.3295078 1.12493092 2003-02-11 -0.8204684 -0.04493361 2003-02-13 0.4874291 -0.01619026 > window(x, index = x.date[1:6], start = as.Date("2003-02-01")) 2003-02-09 0.3295078 1.12493092 2003-02-11 -0.8204684 -0.04493361 > window(x, index = x.date[c(4, 8, 10)]) 2003-01-07 1.5952808 -2.2146999 2003-03-15 0.7383247 0.9438362 2003-04-19 -0.3053884 0.5939013 > window(x, index = x.date[c(4, 8, 10)]) <- matrix(1:6, ncol = 2) > x 2003-01-01 -0.6264538 1.51178117 2003-01-03 0.1836433 0.38984324 2003-01-05 -0.8356286 -0.62124058 2003-01-07 1.0000000 4.00000000 2003-02-09 0.3295078 1.12493092 2003-02-11 -0.8204684 -0.04493361 2003-02-13 0.4874291 -0.01619026 2003-03-15 2.0000000 5.00000000 2003-03-17 0.5757814 0.82122120 2003-04-19 3.0000000 6.00000000 > > ## for classes that support comparisons with "character" variables > ## start and end may be "character". > window(x, start = "2003-02-01") 2003-02-09 0.3295078 1.12493092 2003-02-11 -0.8204684 -0.04493361 2003-02-13 0.4874291 -0.01619026 2003-03-15 2.0000000 5.00000000 2003-03-17 0.5757814 0.82122120 2003-04-19 3.0000000 6.00000000 > > ## zooreg example (with plain numeric index) > z <- zooreg(rnorm(10), start = 2000, freq = 4) > window(z, start = 2001.75) 2001 Q4 2002 Q1 2002 Q2 -1.4707524 -0.4781501 0.4179416 > window(z, start = c(2001, 4)) 2000 Q2 2000 Q4 2001 Q1 2001 Q2 2001 Q3 2001 Q4 0.78213630 -1.98935170 0.61982575 -0.05612874 -0.15579551 -1.47075238 2002 Q1 2002 Q2 -0.47815006 0.41794156 > > ## replace data at times of d0 which are in dn > d1 <- d0 <- zoo(1:10) + 100 > dn <- - head(d0, 4) > window(d1, time(dn)) <- coredata(dn) > > ## if the underlying time index is a float, note that the index may > ## print in the same way but actually be different (e.g., differing > ## by 0.1 second in this example) > zp <- zoo(1:4, as.POSIXct("2000-01-01 00:00:00") + c(-3600, 0, 0.1, 3600)) > ## and then the >= start and <= end may not select all intended > ## observations and adding/subtracting some "fuzz" may be needed > window(zp, end = "2000-01-01 00:00:00") 1999-12-31 23:00:00 2000-01-01 00:00:00 1 2 > window(zp, end = as.POSIXct("2000-01-01 00:00:00") + 0.5) 1999-12-31 23:00:00 2000-01-01 00:00:00 2000-01-01 00:00:00 1 2 3 > > > > cleanEx() > nameEx("xblocks") > ### * xblocks > > flush(stderr()); flush(stdout()) > > ### Name: xblocks > ### Title: Plot contiguous blocks along x axis. > ### Aliases: xblocks xblocks.default xblocks.zoo xblocks.ts > ### Keywords: dplot > > ### ** Examples > > ## example time series: > suppressWarnings(RNGversion("3.5.0")) > set.seed(0) > flow <- ts(filter(rlnorm(200, mean = 1), 0.8, method = "r")) > > ## highlight values above and below thresholds. > ## this draws on top using semi-transparent colors. > rgb <- hcl(c(0, 0, 260), c = c(100, 0, 100), l = c(50, 90, 50), alpha = 0.3) > plot(flow) > xblocks(flow > 30, col = rgb[1]) ## high values red > xblocks(flow < 15, col = rgb[3]) ## low value blue > xblocks(flow >= 15 & flow <= 30, col = rgb[2]) ## the rest gray > > ## same thing: > plot(flow) > xblocks(time(flow), cut(flow, c(0,15,30,Inf), labels = rev(rgb))) > > ## another approach is to plot blocks underneath without transparency. > plot(flow) > ## note that 'ifelse' keeps its result as class 'ts' > xblocks(ifelse(flow < mean(flow), hcl(0, 0, 90), hcl(0, 80, 70))) > ## need to redraw data series on top: > lines(flow) > box() > > ## for single series only: plot.default has a panel.first argument > plot(time(flow), flow, type = "l", + panel.first = xblocks(flow > 20, col = "lightgray")) > ## (see also the 'panel' argument for use with multiple series, below) > > ## insert some missing values > flow[c(1:10, 50:80, 100)] <- NA > > ## the default plot shows data coverage > ## (most useful when displaying multiple series, see below) > plot(flow) > xblocks(flow) > > ## can also show gaps: > plot(flow, type = "s") > xblocks(time(flow), is.na(flow), col = "gray") > > ## Example of alternating colors, here showing calendar months > flowdates <- as.Date("2000-01-01") + as.numeric(time(flow)) > flowz <- zoo(coredata(flow), flowdates) > plot(flowz) > xblocks(flowz, months, ## i.e. months(time(flowz)), + col = gray.colors(2, start = 0.7), border = "slategray") > lines(flowz) > > ## Example of multiple series. > ## set up example data > z <- ts(cbind(A = 0:5, B = c(6:7, NA, NA, 10:11), C = c(NA, 13:17))) > > ## show data coverage only (highlighting gaps) > plot(z, panel = function(x, ...) + xblocks(x, col = "darkgray")) > > ## draw gaps in darkgray > plot(z, type = "s", panel = function(x, ...) { + xblocks(time(x), is.na(x), col = "darkgray") + lines(x, ...); points(x) + }) > > ## Example of overlaying blocks from a different series. > ## Are US presidential approval ratings linked to sunspot activity? > ## Set block height to plot blocks along the bottom. > plot(presidents) > xblocks(sunspot.year > 50, height = 2) > > > > cleanEx() > nameEx("xyplot.zoo") > ### * xyplot.zoo > > flush(stderr()); flush(stdout()) > > ### Name: xyplot.zoo > ### Title: Plot zoo Series with Lattice > ### Aliases: xyplot.zoo xyplot.its xyplot.tis llines.zoo llines.its > ### llines.tis lpoints.zoo lpoints.its lpoints.tis ltext.zoo ltext.its > ### ltext.tis panel.lines.zoo panel.lines.ts panel.lines.its > ### panel.lines.tis panel.points.zoo panel.points.ts panel.points.its > ### panel.points.tis panel.text.zoo panel.text.ts panel.text.its > ### panel.text.tis panel.plot.default panel.plot.custom > ### panel.segments.zoo panel.segments.ts panel.segments.its > ### panel.segments.tis panel.rect.zoo panel.rect.ts panel.rect.its > ### panel.rect.tis panel.polygon.zoo panel.polygon.ts panel.polygon.its > ### panel.polygon.tis > ### Keywords: hplot ts > > ### ** Examples > > if(require("lattice") & require("grid")) { + + suppressWarnings(RNGversion("3.5.0")) + set.seed(1) + z <- zoo(cbind(a = 1:5, b = 11:15, c = 21:25) + rnorm(5)) + + # plot z using same Y axis on all plots + xyplot(z, scales = list(y = list(relation = "same", alternating = FALSE))) + + # plot a double-line-width running mean on the panel of b. + # Also add a grid. + # We show two ways to do it. + + # change strip background to levels of grey + # If you like the defaults, this can be omitted. + strip.background <- trellis.par.get("strip.background") + trellis.par.set(strip.background = list(col = grey(7:1/8))) + + + # Number 1. Using trellis.focus. + print( xyplot(z) ) + trellis.focus("panel", 1, 2, highlight = FALSE) + # (or just trellis.focus() for interactive use) + z.mean <- rollmean(z, 3) + panel.lines(z.mean[,2], lwd = 2) + panel.grid(h = 10, v = 10, col = "grey", lty = 3) + trellis.unfocus() + + # Number 2. Using a custom panel routine. + xyplot(z, panel = function(x, y, ...) { + if (packet.number() == 2) { + panel.grid(h = 10, v = 10, col = "grey", lty = 3) + panel.lines(rollmean(zoo(y, x), 3), lwd = 2) + } + panel.xyplot(x, y, ...) + }) + + # plot a light grey rectangle "behind" panel b + trellis.focus("panel", 1, 2) + grid.rect(x = 2, w = 1, default.units = "native", + gp = gpar(fill = "light grey")) + # do.call("panel.xyplot", trellis.panelArgs()) + do.call("panel.lines", trellis.panelArgs()[1:2]) + trellis.unfocus() + # a better method is to use a custom panel function. + # see also panel.xblocks() and layer() in the latticeExtra package. + + # same but make first panel twice as large as others + lopt <- list(layout.heights = list(panel = list(x = c(2,1,1)))) + xyplot(z, lattice.options = lopt) + # add a grid + update(trellis.last.object(), type = c("l", "g")) + + # Plot all in one panel. + xyplot(z, screens = 1) + # Same with default styles and auto.key: + xyplot(z, superpose = TRUE) + + # Plot first two columns in first panel and third column in second panel. + # Plot first series using points, second series using lines and third + # series via overprinting both lines and points + # Use colors 1, 2 and 3 for the three series (1=black, 2=red, 3=green) + # Make 2nd (lower) panel 3x the height of the 1st (upper) panel + # Also make the strip background orange. + p <- xyplot(z, screens = c(1,1,2), type = c("p", "l", "o"), col = 1:3, + par.settings = list(strip.background = list(col = "orange"))) + print(p, panel.height = list(y = c(1, 3), units = "null")) + + # Example of using a custom axis + # Months are labelled with smaller ticks for weeks and even smaller + # ticks for days. + Days <- seq(from = as.Date("2006-1-1"), to = as.Date("2006-8-8"), by = "day") + z1 <- zoo(seq(length(Days))^2, Days) + Months <- Days[format(Days, "%d") == "01"] + Weeks <- Days[format(Days, "%w") == "0"] + print( xyplot(z1, scales = list(x = list(at = Months))) ) + trellis.focus("panel", 1, 1, clip.off = TRUE) + panel.axis("bottom", check.overlap = TRUE, outside = TRUE, labels = FALSE, + tck = .7, at = as.numeric(Weeks)) + panel.axis("bottom", check.overlap = TRUE, outside = TRUE, labels = FALSE, + tck = .4, at = as.numeric(Days)) + trellis.unfocus() + + trellis.par.set(strip.background = strip.background) + + # separate the panels and suppress the ticks on very top + xyplot(z, between = list(y = 1), scales = list(tck = c(1,0))) + + # left strips but no top strips + xyplot(z, screens = colnames(z), strip = FALSE, strip.left = TRUE) + + # plot list of zoo objects using different x scales + z.l <- list( + zoo(cbind(a = rnorm(10), b = rnorm(10)), as.Date("2006-01-01") + 0:9), + zoo(cbind(c = rnorm(10), d = rnorm(10)), as.Date("2006-12-01") + 0:9) + ) + zm <- do.call(merge, z.l) + xlim <- lapply(zm, function(x) range(time(na.omit(x)))) + xyplot(zm, xlim = xlim, scale = list(relation = "free")) + # to avoid merging see xyplot.list() in the latticeExtra package. + + } Loading required package: lattice Loading required package: grid > > ## Not run: > ##D ## playwith (>= 0.9) > ##D library("playwith") > ##D > ##D z3 <- zoo(cbind(a = rnorm(100), b = rnorm(100) + 1), as.Date(1:100)) > ##D playwith(xyplot(z3), time.mode = TRUE) > ##D # hold down Shift key and drag to zoom in to a time period. > ##D # then use the horizontal scroll bar. > ##D > ##D # set custom labels; right click on points to view or add labels > ##D labs <- paste(round(z3,1), index(z3), sep = "@") > ##D trellis.par.set(user.text = list(cex = 0.7)) > ##D playwith(xyplot(z3, type = "o"), labels = labs) > ##D > ##D # this returns indexes into times of clicked points > ##D ids <- playGetIDs() > ##D z3[ids,] > ##D > ##D ## another example of using playwith with zoo > ##D # set up data > ##D dat <- zoo(matrix(rnorm(100*100),ncol=100), Sys.Date()+1:100) > ##D colnames(dat) <- paste("Series", 1:100) > ##D > ##D # This will give you a spin button to choose the column to plot, > ##D # and a button to print out the current series number. > ##D playwith(xyplot(dat[,c(1,i)]), parameters = list(i = 1:100, > ##D do_something = function(playState) print(playState$env$i)) > ##D > ## End(Not run) > > > > > cleanEx() detaching ‘package:grid’, ‘package:lattice’ > nameEx("yearmon") > ### * yearmon > > flush(stderr()); flush(stdout()) > > ### Name: yearmon > ### Title: An Index Class for Monthly Data > ### Aliases: yearmon as.yearmon as.yearmon.default as.yearmon.numeric > ### as.yearmon.integer as.yearmon.date as.yearmon.dates as.yearmon.Date > ### as.yearmon.timeDate as.yearmon.jul as.yearmon.POSIXt > ### as.yearmon.character as.yearmon.date as.yearmon.factor as.Date > ### as.Date.numeric as.Date.ts as.Date.yearmon as.POSIXct.yearmon > ### as.POSIXlt.yearmon as.list.yearmon as.numeric.yearmon > ### as.character.yearmon as.data.frame.yearmon c.yearmon cycle.yearmon > ### format.yearmon is.numeric.yearmon mean.yearmon print.yearmon > ### range.yearmon summary.yearmon unique.yearmon [.yearmon [[.yearmon > ### MATCH.yearmon Ops.yearmon Summary.yearmon Sys.yearmon -.yearmon > ### xtfrm.yearmon > ### Keywords: ts > > ### ** Examples > > Sys.setenv(TZ = "GMT") > > x <- as.yearmon(2000 + seq(0, 23)/12) > x [1] "Jan 2000" "Feb 2000" "Mar 2000" "Apr 2000" "May 2000" "Jun 2000" [7] "Jul 2000" "Aug 2000" "Sep 2000" "Oct 2000" "Nov 2000" "Dec 2000" [13] "Jan 2001" "Feb 2001" "Mar 2001" "Apr 2001" "May 2001" "Jun 2001" [19] "Jul 2001" "Aug 2001" "Sep 2001" "Oct 2001" "Nov 2001" "Dec 2001" > > as.yearmon("mar07", "%b%y") [1] "Mar 2007" > as.yearmon("2007-03-01") [1] "Mar 2007" > as.yearmon("2007-12") [1] "Dec 2007" > > # returned Date is the fraction of the way through > # the period given by frac (= 0 by default) > as.Date(x) [1] "2000-01-01" "2000-02-01" "2000-03-01" "2000-04-01" "2000-05-01" [6] "2000-06-01" "2000-07-01" "2000-08-01" "2000-09-01" "2000-10-01" [11] "2000-11-01" "2000-12-01" "2001-01-01" "2001-02-01" "2001-03-01" [16] "2001-04-01" "2001-05-01" "2001-06-01" "2001-07-01" "2001-08-01" [21] "2001-09-01" "2001-10-01" "2001-11-01" "2001-12-01" > as.Date(x, frac = 1) [1] "2000-01-31" "2000-02-29" "2000-03-31" "2000-04-30" "2000-05-31" [6] "2000-06-30" "2000-07-31" "2000-08-31" "2000-09-30" "2000-10-31" [11] "2000-11-30" "2000-12-31" "2001-01-31" "2001-02-28" "2001-03-31" [16] "2001-04-30" "2001-05-31" "2001-06-30" "2001-07-31" "2001-08-31" [21] "2001-09-30" "2001-10-31" "2001-11-30" "2001-12-31" > as.POSIXct(x) [1] "2000-01-01 GMT" "2000-02-01 GMT" "2000-03-01 GMT" "2000-04-01 GMT" [5] "2000-05-01 GMT" "2000-06-01 GMT" "2000-07-01 GMT" "2000-08-01 GMT" [9] "2000-09-01 GMT" "2000-10-01 GMT" "2000-11-01 GMT" "2000-12-01 GMT" [13] "2001-01-01 GMT" "2001-02-01 GMT" "2001-03-01 GMT" "2001-04-01 GMT" [17] "2001-05-01 GMT" "2001-06-01 GMT" "2001-07-01 GMT" "2001-08-01 GMT" [21] "2001-09-01 GMT" "2001-10-01 GMT" "2001-11-01 GMT" "2001-12-01 GMT" > > # given a Date, x, return the Date of the next Friday > nextfri <- function(x) 7 * ceiling(as.numeric(x - 1)/7) + as.Date(1) > > # given a Date, d, return the same Date in the following month > # Note that as.Date.yearmon gives first Date of the month. > d <- as.Date("2005-1-1") + seq(0,90,30) > next.month <- function(d) as.Date(as.yearmon(d) + 1/12) + + as.numeric(d - as.Date(as.yearmon(d))) > next.month(d) [1] "2005-02-01" "2005-03-03" "2005-04-02" "2005-05-01" > > # 3rd Friday in last month of the quarter of Date x > ## first day of last month of quarter > y <- as.Date(zoo::as.yearmon(zoo::as.yearqtr(x), frac = 1)) > ## number of days to first Friday > n <- sapply(y, function(z) which(format(z + 0:6, "%w") == "5")) - 1 > ## add number of days to third Friday > y + n + 14 [1] "2000-03-17" "2000-03-17" "2000-03-17" "2000-06-16" "2000-06-16" [6] "2000-06-16" "2000-09-15" "2000-09-15" "2000-09-15" "2000-12-15" [11] "2000-12-15" "2000-12-15" "2001-03-16" "2001-03-16" "2001-03-16" [16] "2001-06-15" "2001-06-15" "2001-06-15" "2001-09-21" "2001-09-21" [21] "2001-09-21" "2001-12-21" "2001-12-21" "2001-12-21" > > > suppressWarnings(RNGversion("3.5.0")) > set.seed(1) > > z <- zoo(rnorm(24), x, frequency = 12) > z Jan 2000 Feb 2000 Mar 2000 Apr 2000 May 2000 Jun 2000 -0.62645381 0.18364332 -0.83562861 1.59528080 0.32950777 -0.82046838 Jul 2000 Aug 2000 Sep 2000 Oct 2000 Nov 2000 Dec 2000 0.48742905 0.73832471 0.57578135 -0.30538839 1.51178117 0.38984324 Jan 2001 Feb 2001 Mar 2001 Apr 2001 May 2001 Jun 2001 -0.62124058 -2.21469989 1.12493092 -0.04493361 -0.01619026 0.94383621 Jul 2001 Aug 2001 Sep 2001 Oct 2001 Nov 2001 Dec 2001 0.82122120 0.59390132 0.91897737 0.78213630 0.07456498 -1.98935170 > as.ts(z) Jan Feb Mar Apr May Jun 2000 -0.62645381 0.18364332 -0.83562861 1.59528080 0.32950777 -0.82046838 2001 -0.62124058 -2.21469989 1.12493092 -0.04493361 -0.01619026 0.94383621 Jul Aug Sep Oct Nov Dec 2000 0.48742905 0.73832471 0.57578135 -0.30538839 1.51178117 0.38984324 2001 0.82122120 0.59390132 0.91897737 0.78213630 0.07456498 -1.98935170 > > ## convert data fram to multivariate monthly "ts" series > ## 1.read raw data > Lines.raw <- "ID Date Count + 123 20 May 1999 1 + 123 21 May 1999 3 + 222 1 Feb 2000 2 + 222 3 Feb 2000 4 + " > DF <- read.table(text = Lines.raw, skip = 1, + col.names = c("ID", "d", "b", "Y", "Count")) > ## 2. fix raw date > DF$yearmon <- as.yearmon(paste(DF$b, DF$Y), "%b %Y") > ## 3. aggregate counts over months, convert to zoo and merge over IDs > ag <- function(DF) aggregate(zoo(DF$Count), DF$yearmon, sum) > z <- do.call("merge.zoo", lapply(split(DF, DF$ID), ag)) > ## 4. convert to "zooreg" and then to "ts" > frequency(z) <- 12 > as.ts(z) 123 222 May 1999 4 NA Jun 1999 NA NA Jul 1999 NA NA Aug 1999 NA NA Sep 1999 NA NA Oct 1999 NA NA Nov 1999 NA NA Dec 1999 NA NA Jan 2000 NA NA Feb 2000 NA 6 > > xx <- zoo(seq_along(x), x) > > ## aggregating over year > as.year <- function(x) as.numeric(floor(as.yearmon(x))) > aggregate(xx, as.year, mean) 2000 2001 6.5 18.5 > > > > > cleanEx() > nameEx("yearqtr") > ### * yearqtr > > flush(stderr()); flush(stdout()) > > ### Name: yearqtr > ### Title: An Index Class for Quarterly Data > ### Aliases: yearqtr as.yearqtr as.yearqtr.default as.yearqtr.numeric > ### as.yearqtr.integer as.yearqtr.date as.yearqtr.dates as.yearqtr.Date > ### as.yearqtr.timeDate as.yearqtr.jul as.yearqtr.POSIXt > ### as.yearqtr.character as.yearqtr.factor as.yearqtr.yearqtr > ### as.Date.yearqtr as.POSIXct.yearqtr as.POSIXlt.yearqtr as.list.yearqtr > ### as.numeric.yearqtr as.character.yearqtr as.data.frame.yearqtr > ### c.yearqtr cycle.yearqtr format.yearqtr is.numeric.yearqtr > ### mean.yearqtr print.yearqtr range.yearqtr summary.yearqtr > ### unique.yearqtr [.yearqtr [[.yearqtr MATCH.yearqtr Ops.yearqtr > ### Summary.yearqtr Sys.yearqtr -.yearqtr xtfrm.yearqtr > ### Keywords: ts > > ### ** Examples > > Sys.setenv(TZ = "GMT") > > x <- as.yearqtr(2000 + seq(0, 7)/4) > x [1] "2000 Q1" "2000 Q2" "2000 Q3" "2000 Q4" "2001 Q1" "2001 Q2" "2001 Q3" [8] "2001 Q4" > > format(x, "%Y Quarter %q") [1] "2000 Quarter 1" "2000 Quarter 2" "2000 Quarter 3" "2000 Quarter 4" [5] "2001 Quarter 1" "2001 Quarter 2" "2001 Quarter 3" "2001 Quarter 4" > as.yearqtr("2001 Q2") [1] "2001 Q2" > as.yearqtr("2001 q2") # same [1] "2001 Q2" > as.yearqtr("2001-2") # same [1] "2001 Q2" > > # returned Date is the fraction of the way through > # the period given by frac (= 0 by default) > dd <- as.Date(x) > format.yearqtr(dd) [1] "2000 Q1" "2000 Q2" "2000 Q3" "2000 Q4" "2001 Q1" "2001 Q2" "2001 Q3" [8] "2001 Q4" > as.Date(x, frac = 1) [1] "2000-03-31" "2000-06-30" "2000-09-30" "2000-12-31" "2001-03-31" [6] "2001-06-30" "2001-09-30" "2001-12-31" > as.POSIXct(x) [1] "2000-01-01 GMT" "2000-04-01 GMT" "2000-07-01 GMT" "2000-10-01 GMT" [5] "2001-01-01 GMT" "2001-04-01 GMT" "2001-07-01 GMT" "2001-10-01 GMT" > > suppressWarnings(RNGversion("3.5.0")) > set.seed(1) > > zz <- zoo(rnorm(8), x, frequency = 4) > zz 2000 Q1 2000 Q2 2000 Q3 2000 Q4 2001 Q1 2001 Q2 2001 Q3 -0.6264538 0.1836433 -0.8356286 1.5952808 0.3295078 -0.8204684 0.4874291 2001 Q4 0.7383247 > as.ts(zz) Qtr1 Qtr2 Qtr3 Qtr4 2000 -0.6264538 0.1836433 -0.8356286 1.5952808 2001 0.3295078 -0.8204684 0.4874291 0.7383247 > > > > > cleanEx() > nameEx("zoo") > ### * zoo > > flush(stderr()); flush(stdout()) > > ### Name: zoo > ### Title: Z's Ordered Observations > ### Aliases: zoo with.zoo range.zoo print.zoo as.zoo.factor summary.zoo > ### str.zoo is.zoo [.zoo [<-.zoo $.zoo $<-.zoo subset.zoo head.zoo > ### tail.zoo Ops.zoo t.zoo cumsum.zoo cumprod.zoo cummin.zoo cummax.zoo > ### mean.zoo median.zoo na.contiguous na.contiguous.data.frame > ### na.contiguous.list na.contiguous.default na.contiguous.zoo scale.zoo > ### xtfrm.zoo names.zoo names<-.zoo quantile.zoo rev.zoo transform.zoo > ### ifelse.zoo dim<-.zoo index2char index2char.default index2char.numeric > ### index2char.POSIXt head.ts tail.ts > ### Keywords: ts > > ### ** Examples > > suppressWarnings(RNGversion("3.5.0")) > set.seed(1) > > ## simple creation and plotting > x.Date <- as.Date("2003-02-01") + c(1, 3, 7, 9, 14) - 1 > x <- zoo(rnorm(5), x.Date) > plot(x) > time(x) [1] "2003-02-01" "2003-02-03" "2003-02-07" "2003-02-09" "2003-02-14" > > ## subsetting with numeric indexes > x[c(2, 4)] 2003-02-03 2003-02-09 0.1836433 1.5952808 > ## subsetting with index class > x[as.Date("2003-02-01") + c(2, 8)] 2003-02-03 2003-02-09 0.1836433 1.5952808 > > ## different classes of indexes/times can be used, e.g. numeric vector > x <- zoo(rnorm(5), c(1, 3, 7, 9, 14)) > ## subsetting with numeric indexes then uses observation numbers > x[c(2, 4)] 3 9 0.4874291 0.5757814 > ## subsetting with index class can be enforced by I() > x[I(c(3, 9))] 3 9 0.4874291 0.5757814 > > ## visualization > plot(x) > ## or POSIXct > y.POSIXct <- ISOdatetime(2003, 02, c(1, 3, 7, 9, 14), 0, 0, 0) > y <- zoo(rnorm(5), y.POSIXct) > plot(y) > > ## create a constant series > z <- zoo(1, seq(4)[-2]) > > ## create a 0-dimensional zoo series > z0 <- zoo(, 1:4) > > ## create a 2-dimensional zoo series > z2 <- zoo(matrix(1:12, 4, 3), as.Date("2003-01-01") + 0:3) > > ## create a factor zoo object > fz <- zoo(gl(2,5), as.Date("2004-01-01") + 0:9) > > ## create a zoo series with 0 columns > z20 <- zoo(matrix(nrow = 4, ncol = 0), 1:4) > > ## arithmetic on zoo objects intersects them first > x1 <- zoo(1:5, 1:5) > x2 <- zoo(2:6, 2:6) > 10 * x1 + x2 2 3 4 5 22 33 44 55 > > ## $ extractor for multivariate zoo series with column names > z <- zoo(cbind(foo = rnorm(5), bar = rnorm(5))) > z$foo 1 2 3 4 5 -0.04493361 -0.01619026 0.94383621 0.82122120 0.59390132 > z$xyz <- zoo(rnorm(3), 2:4) > z foo bar xyz 1 -0.04493361 0.91897737 NA 2 -0.01619026 0.78213630 -0.05612874 3 0.94383621 0.07456498 -0.15579551 4 0.82122120 -1.98935170 -1.47075238 5 0.59390132 0.61982575 NA > > ## add comments to a zoo object > comment(x1) <- c("This is a very simple example of a zoo object.", + "It can be recreated using this R code: example(zoo)") > ## comments are not output by default but are still there > x1 1 2 3 4 5 1 2 3 4 5 > comment(x1) [1] "This is a very simple example of a zoo object." [2] "It can be recreated using this R code: example(zoo)" > > # ifelse does not work with zoo but this works > # to create a zoo object which equals x1 at > # time i if x1[i] > x1[i-1] and 0 otherwise > (diff(x1) > 0) * x1 2 3 4 5 2 3 4 5 > > ## zoo series with duplicated indexes > z3 <- zoo(1:8, c(1, 2, 2, 2, 3, 4, 5, 5)) Warning in zoo(1:8, c(1, 2, 2, 2, 3, 4, 5, 5)) : some methods for “zoo” objects do not work if the index entries in ‘order.by’ are not unique > plot(z3) > ## remove duplicated indexes by averaging > lines(aggregate(z3, index(z3), mean), col = 2) > ## or by using the last observation > lines(aggregate(z3, index(z3), tail, 1), col = 4) > > ## x1[x1 > 3] is not officially supported since > ## x1 > 3 is of class "zoo", not "logical". > ## Use one of these instead: > x1[which(x1 > 3)] 4 5 4 5 > x1[coredata(x1 > 3)] 4 5 4 5 > x1[as.logical(x1 > 3)] 4 5 4 5 > subset(x1, x1 > 3) 4 5 4 5 > > ## any class supporting the methods discussed can be used > ## as an index class. Here are examples using complex numbers > ## and letters as the time class. > > z4 <- zoo(11:15, complex(real = c(1, 3, 4, 5, 6), imag = c(0, 1, 0, 0, 1))) > merge(z4, lag(z4)) z4 lag(z4) 1+0i 11 12 3+1i 12 13 4+0i 13 14 5+0i 14 15 6+1i 15 NA > > z5 <- zoo(11:15, letters[1:5]) > merge(z5, lag(z5)) z5 lag(z5) a 11 12 b 12 13 c 13 14 d 14 15 e 15 NA > > # index values relative to 2001Q1 > zz <- zooreg(cbind(a = 1:10, b = 11:20), start = as.yearqtr(2000), freq = 4) > zz[] <- mapply("/", as.data.frame(zz), coredata(zz[as.yearqtr("2001Q1")])) > > > ## even though time index must be unique zoo (and read.zoo) > ## will both allow creation of such illegal objects with > ## a warning (rather than ana error) to give the user a > ## chance to fix them up. Extracting and replacing times > ## and aggregate.zoo will still work. > ## Not run: > ##D # this gives a warning > ##D # and then creates an illegal zoo object > ##D z6 <- zoo(11:15, c(1, 1, 2, 2, 5)) > ##D z6 > ##D > ##D # fix it up by averaging duplicates > ##D aggregate(z6, identity, mean) > ##D > ##D # or, fix it up by taking last in each set of duplicates > ##D aggregate(z6, identity, tail, 1) > ##D > ##D # fix it up via interpolation of duplicate times > ##D time(z6) <- na.approx(ifelse(duplicated(time(z6)), NA, time(z6)), na.rm = FALSE) > ##D # if there is a run of equal times at end they > ##D # wind up as NAs and we cannot have NA times > ##D z6 <- z6[!is.na(time(z6))] > ##D z6 > ##D > ##D x1. <- x1 <- zoo (matrix (1:12, nrow = 3), as.Date("2008-08-01") + 0:2) > ##D colnames (x1) <- c ("A", "B", "C", "D") > ##D x2 <- zoo (matrix (1:12, nrow = 3), as.Date("2008-08-01") + 1:3) > ##D colnames (x2) <- c ("B", "C", "D", "E") > ##D > ##D both.dates = as.Date (intersect (index (t1), index (t2))) > ##D both.cols = intersect (colnames (t1), colnames (t2)) > ##D > ##D x1[both.dates, both.cols] > ##D ## there is "[.zoo" but no "[<-.zoo" however four of the following > ##D ## five examples work > ##D > ##D ## wrong > ##D ## x1[both.dates, both.cols] <- x2[both.dates, both.cols] > ##D > ##D # 4 correct alternatives > ##D # #1 > ##D window(x1, both.dates)[, both.cols] <- x2[both.dates, both.cols] > ##D > ##D # #2. restore x1 and show a different way > ##D x1 <- x1. > ##D window(x1, both.dates)[, both.cols] <- window(x2, both.dates)[, both.cols] > ##D > ##D # #3. restore x1 and show a different way > ##D x1 <- x1. > ##D x1[time(x1) ##D > ##D > ##D # #4. restore x1 and show a different way > ##D x1 <- x1. > ##D x1[time(x1) ##D > ##D > ## End(Not run) > > > > > cleanEx() > nameEx("zooreg") > ### * zooreg > > flush(stderr()); flush(stdout()) > > ### Name: zooreg > ### Title: Regular zoo Series > ### Aliases: zooreg frequency.zooreg frequency.zoo deltat.zooreg deltat.zoo > ### cycle.zooreg cycle.zoo as.zooreg as.zooreg.default as.zooreg.ts > ### as.zooreg.its as.zooreg.xts as.ts.zooreg as.zoo.zooreg as.zooreg.zoo > ### index<-.zooreg time<-.zooreg lag.zooreg > ### Keywords: ts > > ### ** Examples > > ## equivalent specifications of a quarterly series > ## starting in the second quarter of 1959. > zooreg(1:10, frequency = 4, start = c(1959, 2)) 1959 Q2 1959 Q3 1959 Q4 1960 Q1 1960 Q2 1960 Q3 1960 Q4 1961 Q1 1961 Q2 1961 Q3 1 2 3 4 5 6 7 8 9 10 > as.zoo(ts(1:10, frequency = 4, start = c(1959, 2))) 1959 Q2 1959 Q3 1959 Q4 1960 Q1 1960 Q2 1960 Q3 1960 Q4 1961 Q1 1961 Q2 1961 Q3 1 2 3 4 5 6 7 8 9 10 > zoo(1:10, seq(1959.25, 1961.5, by = 0.25), frequency = 4) 1959 Q2 1959 Q3 1959 Q4 1960 Q1 1960 Q2 1960 Q3 1960 Q4 1961 Q1 1961 Q2 1961 Q3 1 2 3 4 5 6 7 8 9 10 > > ## use yearqtr class for indexing the same series > z <- zoo(1:10, yearqtr(seq(1959.25, 1961.5, by = 0.25)), frequency = 4) > z 1959 Q2 1959 Q3 1959 Q4 1960 Q1 1960 Q2 1960 Q3 1960 Q4 1961 Q1 1961 Q2 1961 Q3 1 2 3 4 5 6 7 8 9 10 > z[-(3:4)] 1959 Q2 1959 Q3 1960 Q2 1960 Q3 1960 Q4 1961 Q1 1961 Q2 1961 Q3 1 2 5 6 7 8 9 10 > > ## create a regular series with a "Date" index > zooreg(1:5, start = as.Date("2000-01-01")) 2000-01-01 2000-01-02 2000-01-03 2000-01-04 2000-01-05 1 2 3 4 5 > ## or with "yearmon" index > zooreg(1:5, end = yearmon(2000)) Jan 1996 Jan 1997 Jan 1998 Jan 1999 Jan 2000 1 2 3 4 5 > > ## lag and diff (as diff is defined in terms of lag) > ## act differently on zoo and zooreg objects! > ## lag.zoo moves a point to the adjacent time whereas > ## lag.zooreg moves a point by deltat > x <- c(1, 2, 3, 6) > zz <- zoo(x, x) > zr <- as.zooreg(zz) > lag(zz, k = -1) 2 3 6 1 2 3 > lag(zr, k = -1) 2 3 4 7 1 2 3 6 > diff(zz) 2 3 6 1 1 3 > diff(zr) 2 3 1 1 > > ## lag.zooreg wihtout and with na.pad > lag(zr, k = -1) 2 3 4 7 1 2 3 6 > lag(zr, k = -1, na.pad = TRUE) 1 2 3 4 6 7 NA 1 2 3 NA 6 > > ## standard methods available for regular series > frequency(z) [1] 4 > deltat(z) [1] 0.25 > cycle(z) 1959 Q2 1959 Q3 1959 Q4 1960 Q1 1960 Q2 1960 Q3 1960 Q4 1961 Q1 1961 Q2 1961 Q3 2 3 4 1 2 3 4 1 2 3 > cycle(z[-(3:4)]) 1959 Q2 1959 Q3 1960 Q2 1960 Q3 1960 Q4 1961 Q1 1961 Q2 1961 Q3 2 3 2 3 4 1 2 3 > > zz <- zoo(1:6, as.Date(c("1960-01-29", "1960-02-29", "1960-03-31", + "1960-04-29", "1960-05-31", "1960-06-30"))) > # this converts zz to "zooreg" and then to "ts" expanding it to a daily > # series which is 154 elements long, most with NAs. > ## Not run: > ##D length(as.ts(zz)) # 154 > ## End(Not run) > # probably a monthly "ts" series rather than a daily one was wanted. > # This variation of the last line gives a result only 6 elements long. > length(as.ts(aggregate(zz, as.yearmon, c))) # 6 [1] 6 > > zzr <- as.zooreg(zz) > > dd <- as.Date(c("2000-01-01", "2000-02-01", "2000-03-01", "2000-04-01")) > zrd <- as.zooreg(zoo(1:4, dd)) > > > > > ### *