├── DESCRIPTION ├── MD5 ├── NAMESPACE ├── NEWS ├── R ├── MATCH.R ├── ORDER.R ├── Ops.zoo.R ├── aggregate.zoo.R ├── as.Date.R ├── as.Date.ts.R ├── as.zoo.R ├── as.zoo.tis.R ├── barplot.zoo.R ├── coredata.R ├── ggplot2.zoo.R ├── index.R ├── index2char.R ├── is.regular.R ├── merge.zoo.R ├── na.StructTS.R ├── na.aggregate.R ├── na.approx.R ├── na.fill.R ├── na.locf.R ├── na.spline.R ├── na.trim.R ├── plot.zoo.R ├── read.zoo.R ├── rollapply.R ├── rollmean.R ├── tinyplot.zoo.R ├── window.zoo.R ├── xblocks.R ├── xyplot.zoo.R ├── yearmon.R ├── yearqtr.R ├── zoo.R ├── zooreg.R └── zzz.R ├── build └── vignette.rds ├── demo ├── 00Index └── zoo-overplot.R ├── inst ├── CITATION ├── THANKS ├── TODO ├── WISHLIST ├── doc │ ├── MSFT.rda │ ├── demo1.txt │ ├── demo2.txt │ ├── msft2004.rda │ ├── sunw.rda │ ├── zoo-design.R │ ├── zoo-design.Rnw │ ├── zoo-design.pdf │ ├── zoo-faq.R │ ├── zoo-faq.Rnw │ ├── zoo-faq.pdf │ ├── zoo-quickref.R │ ├── zoo-quickref.Rnw │ ├── zoo-quickref.pdf │ ├── zoo-read.R │ ├── zoo-read.Rnw │ ├── zoo-read.pdf │ ├── zoo.R │ ├── zoo.Rnw │ └── zoo.pdf └── include │ └── zoo.h ├── man ├── MATCH.Rd ├── ORDER.Rd ├── aggregate.zoo.Rd ├── as.zoo.Rd ├── coredata.Rd ├── frequency.Rd ├── ggplot2.zoo.Rd ├── index.Rd ├── is.regular.Rd ├── lag.zoo.Rd ├── make.par.list.Rd ├── merge.zoo.Rd ├── na.StructTS.Rd ├── na.aggregate.Rd ├── na.approx.Rd ├── na.fill.Rd ├── na.locf.Rd ├── na.trim.Rd ├── plot.zoo.Rd ├── read.zoo.Rd ├── rollapply.Rd ├── rollmean.Rd ├── tinyplot.zoo.Rd ├── window.zoo.Rd ├── xblocks.Rd ├── xyplot.zoo.Rd ├── yearmon.Rd ├── yearqtr.Rd ├── zoo.Rd └── zooreg.Rd ├── src ├── Makevars ├── Makevars.win ├── coredata.c ├── init.c └── lag.c ├── tests ├── Examples │ └── zoo-Ex.Rout.save ├── as.Date.R ├── as.Date.Rout.save ├── bugfixes.R ├── bugfixes.Rout.save ├── na.fill.R ├── na.fill.Rout.save ├── na.locf.R ├── na.locf.Rout.save ├── vignette-zoo-quickref.R ├── vignette-zoo-quickref.Rout.save ├── vignette-zoo.R └── vignette-zoo.Rout.save └── vignettes ├── .install_extras ├── MSFT.rda ├── demo1.txt ├── demo2.txt ├── msft2004.rda ├── sunw.rda ├── zoo-design.Rnw ├── zoo-faq.Rnw ├── zoo-quickref.Rnw ├── zoo-read.Rnw ├── zoo-refcard-raw.tex ├── zoo-refcard.pdf ├── zoo-refcard.tex ├── zoo.Rnw └── zoo.bib /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: zoo 2 | Version: 1.8-14 3 | Date: 2025-04-09 4 | Title: S3 Infrastructure for Regular and Irregular Time Series (Z's 5 | Ordered Observations) 6 | Authors@R: c(person(given = "Achim", family = "Zeileis", role = c("aut", "cre"), email = "Achim.Zeileis@R-project.org", 7 | comment = c(ORCID = "0000-0003-0918-3766")), 8 | person(given = "Gabor", family = "Grothendieck", role = "aut", email = "ggrothendieck@gmail.com"), 9 | person(given = c("Jeffrey", "A."), family = "Ryan", role = "aut", email = "jeff.a.ryan@gmail.com"), 10 | person(given = c("Joshua", "M."), family = "Ulrich", role = "ctb", email = "josh.m.ulrich@gmail.com"), 11 | person(given = "Felix", family = "Andrews", role = "ctb", email = "felix@nfrac.org")) 12 | Description: An S3 class with methods for totally ordered indexed 13 | observations. It is particularly aimed at irregular time series 14 | of numeric vectors/matrices and factors. zoo's key design goals 15 | are independence of a particular index/date/time class and 16 | consistency with ts and base R by providing methods to extend 17 | standard generics. 18 | Depends: R (>= 3.1.0), stats 19 | Suggests: AER, coda, chron, ggplot2 (>= 3.5.0), mondate, scales, 20 | stinepack, strucchange, timeDate, timeSeries, tinyplot, tis, 21 | tseries, xts 22 | Imports: utils, graphics, grDevices, lattice (>= 0.20-27) 23 | License: GPL-2 | GPL-3 24 | URL: https://zoo.R-Forge.R-project.org/ 25 | NeedsCompilation: yes 26 | Packaged: 2025-04-09 16:51:51 UTC; zeileis 27 | Author: Achim Zeileis [aut, cre] (), 28 | Gabor Grothendieck [aut], 29 | Jeffrey A. Ryan [aut], 30 | Joshua M. Ulrich [ctb], 31 | Felix Andrews [ctb] 32 | Maintainer: Achim Zeileis 33 | Repository: CRAN 34 | Date/Publication: 2025-04-10 06:40:02 UTC 35 | -------------------------------------------------------------------------------- /MD5: -------------------------------------------------------------------------------- 1 | 599f6a267c302e3b9ebcd9e3b3850dd4 *DESCRIPTION 2 | f2f481a274bf338de0619a5be2848ceb *NAMESPACE 3 | a337f0f4dcce6828cfb01c1b9b5ca16b *NEWS 4 | 7ecaff55c2ae98b77d24c4b6c7f7cf86 *R/MATCH.R 5 | 3eebd5fe3394080789fedfea3a45e3ab *R/ORDER.R 6 | 9015ff069b28219b6dc44505641d249c *R/Ops.zoo.R 7 | 5c3f54c4c9d2692046b3b1049fc771f8 *R/aggregate.zoo.R 8 | 65b001243ba9e0edf4c03e60bad35129 *R/as.Date.R 9 | 93ff2d240541d0aa3588d410eb235699 *R/as.Date.ts.R 10 | 6db32948738cea952f50629e41e0969b *R/as.zoo.R 11 | 62c1bf87a7380c654f17b1b8ed71efc6 *R/as.zoo.tis.R 12 | faaae6520bab57abe84eaa00ee3ad414 *R/barplot.zoo.R 13 | 5af291cb99c193b4db3fc89ac9a59cff *R/coredata.R 14 | 673b6e421d61084b134a30a1c6958727 *R/ggplot2.zoo.R 15 | 04a26dde3202887ef53a4b78a8e49830 *R/index.R 16 | 4eb9cb572803b612e1735713d0d4fdce *R/index2char.R 17 | 1d215aeb25acc0c75a6321f0522e2a76 *R/is.regular.R 18 | bdb3ac5e66c6b34351c21dba99ca4c51 *R/merge.zoo.R 19 | 7564a94e7eb8117617e4433e69f0b50b *R/na.StructTS.R 20 | 4e8c25337f2e1891e0939ebf2e6b0138 *R/na.aggregate.R 21 | 824be88c3d276757f34bf4792223a4f6 *R/na.approx.R 22 | 4ed0e2f08381ac59978b36893db30e5a *R/na.fill.R 23 | cd801f2e256a937016dfa229969ae118 *R/na.locf.R 24 | 7682d00afdbff36fd903883d4df687a3 *R/na.spline.R 25 | e1693ddba5cb8a6c55839564b02d80bd *R/na.trim.R 26 | 128409c63979259e0ccb526e00a2262b *R/plot.zoo.R 27 | 3e0089ad159aa072d3e57b071017ad44 *R/read.zoo.R 28 | f961d86ef885dc7641d30380917b4919 *R/rollapply.R 29 | 975b201ae4e5746503ac0fea981e4a4d *R/rollmean.R 30 | da7d270242646bd12f627b43ae283fe0 *R/tinyplot.zoo.R 31 | fed032087f2b3973825d0b945d189cb8 *R/window.zoo.R 32 | f00456b37d08ed0da5cd43756e2cf4ea *R/xblocks.R 33 | e453aed85b5d4c2a69e8bda7a7fb2f0d *R/xyplot.zoo.R 34 | 23d83669191cd8c22d45a04581475623 *R/yearmon.R 35 | 5c06382741ad2de47bf11056e52cedc1 *R/yearqtr.R 36 | 0c2817c7040a2d175f2353c2a5342be6 *R/zoo.R 37 | 6ce3a445569bd5081a41a2eeca68188e *R/zooreg.R 38 | 2384093e877b896e17e0a4db2880d81a *R/zzz.R 39 | 3b9853af5b97e970524a9b0f0b1b9fa6 *build/vignette.rds 40 | beb8720082847566abaa78c65ee97815 *demo/00Index 41 | 1c04abe2bd67fe9ba55d6e1ac3e73cab *demo/zoo-overplot.R 42 | 46c8080b0ab7f4edc4b376cdd984329d *inst/CITATION 43 | 21bede1b02820b648012773b5d3994fe *inst/THANKS 44 | bdc15aaa93d42a0e813dbca29806940a *inst/TODO 45 | e3acf3d51204abf03613d4db414a318d *inst/WISHLIST 46 | 965dc0e909a6be66370cdfd3b7732589 *inst/doc/MSFT.rda 47 | a916af484ffa11d8aa8669404a25e53c *inst/doc/demo1.txt 48 | 5ad2a643bb73c28764fd4db6db457261 *inst/doc/demo2.txt 49 | 80e53a8d998cfa5a0e349815d5b61d40 *inst/doc/msft2004.rda 50 | 8ab6ae33767b9f99c8158192e12832c1 *inst/doc/sunw.rda 51 | e90680abb6a7cd9bd8de0e07667711b7 *inst/doc/zoo-design.R 52 | 5051eb1d34cd0d183e2d84449912c9f8 *inst/doc/zoo-design.Rnw 53 | b62f195b24f5bb3f7fad40a5c8c71c90 *inst/doc/zoo-design.pdf 54 | f258743c6f42e2f350f04b0a5354fa8b *inst/doc/zoo-faq.R 55 | abeb6951c1dda54c9f394191dee37559 *inst/doc/zoo-faq.Rnw 56 | 8f4e2fba9d06fa4461ec934d42c4eae2 *inst/doc/zoo-faq.pdf 57 | cb46b30f77223c769a138f122d1e395b *inst/doc/zoo-quickref.R 58 | 556795343c5812cbdaca53d8c397d9fc *inst/doc/zoo-quickref.Rnw 59 | 96cb92c480fd78052508b0ad4f63ffb3 *inst/doc/zoo-quickref.pdf 60 | 215cdf1689e8833ce94f0f41544ae2a6 *inst/doc/zoo-read.R 61 | ef8670bffd8c57b5ac6c07268f0d3780 *inst/doc/zoo-read.Rnw 62 | 87d818d66a4af00b4e2f3c8923a25c07 *inst/doc/zoo-read.pdf 63 | 429aa6375a73f63cf9fc2ce2e8acbbf5 *inst/doc/zoo.R 64 | 3d840df3e07f146981d4b6ef17ddf275 *inst/doc/zoo.Rnw 65 | 9dd4853f222f480d375cd10733556bb1 *inst/doc/zoo.pdf 66 | dd2909911733f11d02837283e885402e *inst/include/zoo.h 67 | 049de4bce6d54e1245d1f717d46aa214 *man/MATCH.Rd 68 | ce5614980ae640df7c8388f72de3a0ca *man/ORDER.Rd 69 | bd9c7117b3bc57122236527f00764538 *man/aggregate.zoo.Rd 70 | 9f4520c0da898b2c1015214ad0983a09 *man/as.zoo.Rd 71 | e4d5e73b04ea219a68758f5e418cf03d *man/coredata.Rd 72 | a91c3b70c28fc5e49376918e6f963781 *man/frequency.Rd 73 | 5065376bc3450e37674ae5c4b78f6980 *man/ggplot2.zoo.Rd 74 | 0ee53f3c9dd874f11810b2bf48cd2286 *man/index.Rd 75 | 8cf1931a2b0bf69932742baa3888633f *man/is.regular.Rd 76 | 8ad8775a0e6fb6c6060842d734da5d42 *man/lag.zoo.Rd 77 | 2a40905ca067abf2ac4b679c6e12748a *man/make.par.list.Rd 78 | d5804e44041b14e96488a436b76f6e48 *man/merge.zoo.Rd 79 | 3c0fb563ffd6d9c834a2bea15add16e4 *man/na.StructTS.Rd 80 | d2c2255460d224a4a7c332f5c03cce4c *man/na.aggregate.Rd 81 | 12a2b5866170ca6d3266eb04909ee844 *man/na.approx.Rd 82 | 66d62e138e0f96bd2cc8952137fdd163 *man/na.fill.Rd 83 | 7b46c69ea0c6188d3de8e892b44b9b1d *man/na.locf.Rd 84 | 7704bdd731f89c3ec80e67a146a68b3d *man/na.trim.Rd 85 | 89f9d3483cc1a8cde72f6b4180806ffb *man/plot.zoo.Rd 86 | f8f1f2a0bded275bc26965973ab98ce1 *man/read.zoo.Rd 87 | a01d3360c362844e5670fc6eac28e333 *man/rollapply.Rd 88 | 54b25508c987d090386d6bb32de4887b *man/rollmean.Rd 89 | 67782c6ea8858eedacc7df488b80e80e *man/tinyplot.zoo.Rd 90 | bc80d93adebdb275b6ebea39413a1c14 *man/window.zoo.Rd 91 | 1b447893b54d8ec70f5b7d1bd3b7d73c *man/xblocks.Rd 92 | fa0c77d6ec2433b0a48a9f6b481b3180 *man/xyplot.zoo.Rd 93 | c95a76b45fb16620dd57876f5a3fa1ba *man/yearmon.Rd 94 | 9f07c8b098764cf10678e2bcccc98afe *man/yearqtr.Rd 95 | bbc7b0d935166171a52ac1ce552c6249 *man/zoo.Rd 96 | 58ee858545582658d9d7b4f7532b4e7e *man/zooreg.Rd 97 | 3f03da795dd26373156bddc78d41e95d *src/Makevars 98 | 3f03da795dd26373156bddc78d41e95d *src/Makevars.win 99 | 132711221439cc019865622951f728f3 *src/coredata.c 100 | d80f53271535df8c5070377e897052cc *src/init.c 101 | 14f00337dca1c8b7805a8067f03ba07e *src/lag.c 102 | d7b68de170b22effe69cf1d3c1ca84a7 *tests/Examples/zoo-Ex.Rout.save 103 | cbea17222fe8d8f0846e1ec28ab2b987 *tests/as.Date.R 104 | 1882571886517203f54502bc1f8b3fac *tests/as.Date.Rout.save 105 | 3208e41199e2d233f5d1272f58d0fd9f *tests/bugfixes.R 106 | 0cbfa36f15b7cfae60c5278ea06aed68 *tests/bugfixes.Rout.save 107 | a905c3b6527f98e35f3704803b56c00a *tests/na.fill.R 108 | 273eeeb67fe48d77f750f25e4c0343c3 *tests/na.fill.Rout.save 109 | fc03ca37812f8044b2dd0b73c193a0c1 *tests/na.locf.R 110 | c707866a03cde5be1b68b84a0c2f67cc *tests/na.locf.Rout.save 111 | 06e29fdd93455451f7a42fd9aa11aae3 *tests/vignette-zoo-quickref.R 112 | e87f0dba3fed83dd73c70718308ac757 *tests/vignette-zoo-quickref.Rout.save 113 | 8e4091815e9b7d96f5b3d3c95be00fc9 *tests/vignette-zoo.R 114 | acc7fb1bcb485d5da690af2805e46caa *tests/vignette-zoo.Rout.save 115 | 965dc0e909a6be66370cdfd3b7732589 *vignettes/MSFT.rda 116 | a916af484ffa11d8aa8669404a25e53c *vignettes/demo1.txt 117 | 5ad2a643bb73c28764fd4db6db457261 *vignettes/demo2.txt 118 | 80e53a8d998cfa5a0e349815d5b61d40 *vignettes/msft2004.rda 119 | 8ab6ae33767b9f99c8158192e12832c1 *vignettes/sunw.rda 120 | 5051eb1d34cd0d183e2d84449912c9f8 *vignettes/zoo-design.Rnw 121 | abeb6951c1dda54c9f394191dee37559 *vignettes/zoo-faq.Rnw 122 | 556795343c5812cbdaca53d8c397d9fc *vignettes/zoo-quickref.Rnw 123 | ef8670bffd8c57b5ac6c07268f0d3780 *vignettes/zoo-read.Rnw 124 | cabf2181f83a8594f4e0e1cd18f3367f *vignettes/zoo-refcard-raw.tex 125 | ecc325b9e45907aa10e771f4cd578a2f *vignettes/zoo-refcard.pdf 126 | ef7fd243ec57bc81c59c22bad0214916 *vignettes/zoo-refcard.tex 127 | 3d840df3e07f146981d4b6ef17ddf275 *vignettes/zoo.Rnw 128 | d6e8c65cf8a2b2450a30de741aa742c0 *vignettes/zoo.bib 129 | -------------------------------------------------------------------------------- /R/MATCH.R: -------------------------------------------------------------------------------- 1 | MATCH <- function(x, table, nomatch = NA, ...) 2 | UseMethod("MATCH") 3 | 4 | MATCH.default <- function(x, table, nomatch = NA, ...) { 5 | if(is.atomic(x) && !is.object(x)) { 6 | if(inherits(table, "Date")) { 7 | x <- unclass(as.Date(x, origin = "1970-01-01")) 8 | table <- unclass(table) 9 | } else if(inherits(table, "POSIXt")) { 10 | x <- unclass(as.POSIXct(x, origin = "1970-01-01")) 11 | table <- unclass(as.POSIXct(table)) 12 | } 13 | } 14 | match(x, table, nomatch = nomatch, ...) 15 | } 16 | 17 | MATCH.timeDate <- function(x, table, nomatch = NA, ...) { 18 | match(as.POSIXct(x), as.POSIXct(table), nomatch = nomatch, ...) 19 | } 20 | 21 | MATCH.times <- function(x, table, nomatch = NA, units = "sec", eps = 1e-10, ...) { 22 | match(trunc(x, units, eps), trunc(table, units, eps), nomatch = nomatch, ...) 23 | } 24 | 25 | MATCH.Date <- function(x, table, nomatch = NA, ...) { 26 | if(!inherits(table, "Date")) table <- as.Date(table) 27 | match(unclass(x), unclass(table), nomatch = nomatch, ...) 28 | } 29 | 30 | MATCH.POSIXct <- function(x, table, nomatch = NA, ...) { 31 | if(!inherits(table, "POSIXct")) table <- as.POSIXct(table) 32 | match(unclass(x), unclass(table), nomatch = nomatch, ...) 33 | } 34 | 35 | MATCH.POSIXlt <- function(x, table, nomatch = NA, ...) { 36 | x <- as.POSIXct(x) 37 | if(!inherits(table, "POSIXct")) table <- as.POSIXct(table) 38 | match(unclass(x), unclass(table), nomatch = nomatch, ...) 39 | } 40 | -------------------------------------------------------------------------------- /R/ORDER.R: -------------------------------------------------------------------------------- 1 | ORDER <- function(x, ...) 2 | UseMethod("ORDER") 3 | 4 | ORDER.default <- function(x, ..., na.last = TRUE, decreasing = FALSE) 5 | order(x, ..., na.last = na.last, decreasing = decreasing) 6 | 7 | ORDER.timeDate <- function(x, ...) { 8 | order(as.POSIXct(x), ...) 9 | } 10 | 11 | ORDER.chron <- ORDER.dates <- ORDER.times <- function(x, ...) { 12 | order(as.numeric(x), ...) 13 | } 14 | -------------------------------------------------------------------------------- /R/Ops.zoo.R: -------------------------------------------------------------------------------- 1 | Ops.zoo <- function (e1, e2) 2 | { 3 | e <- if (missing(e2)) { 4 | NextMethod(.Generic) 5 | } 6 | else if (any(nchar(.Method) == 0L)) { 7 | NextMethod(.Generic) 8 | } 9 | else { 10 | merge(e1, e2, all = FALSE, retclass = NULL) 11 | NextMethod(.Generic) 12 | } 13 | if (is.null(attr(e, "index"))) { 14 | if(!missing(e2) && nchar(.Method)[1L] == 0L) { 15 | out <- zoo(e, index(e2), attr(e2, "frequency")) 16 | } else { 17 | out <- zoo(e, index(e1), attr(e1, "frequency")) 18 | } 19 | } else { 20 | out <- e 21 | } 22 | # the next statement is a workaround for a bug in R 23 | structure(out, class = class(out)) 24 | } 25 | 26 | t.zoo <- function(x) 27 | t(as.matrix.zoo(x)) 28 | 29 | cumsum.zoo <- function(x) 30 | { 31 | if (length(dim(x)) == 0) x[] <- cumsum(coredata(x)) 32 | else x[] <- apply(coredata(x), 2, cumsum) 33 | return(x) 34 | } 35 | 36 | 37 | cumprod.zoo <- function(x) 38 | { 39 | if (length(dim(x)) == 0) x[] <- cumprod(coredata(x)) 40 | else x[] <- apply(coredata(x), 2, cumprod) 41 | return(x) 42 | } 43 | 44 | 45 | cummin.zoo <- function(x) 46 | { 47 | if (length(dim(x)) == 0) x[] <- cummin(coredata(x)) 48 | else x[] <- apply(coredata(x), 2, cummin) 49 | return(x) 50 | } 51 | 52 | 53 | cummax.zoo <- function(x) 54 | { 55 | if (length(dim(x)) == 0) x[] <- cummax(coredata(x)) 56 | else x[] <- apply(coredata(x), 2, cummax) 57 | return(x) 58 | } 59 | -------------------------------------------------------------------------------- /R/aggregate.zoo.R: -------------------------------------------------------------------------------- 1 | aggregate.zoo <- function(x, by, FUN = sum, ..., regular = NULL, frequency = NULL, coredata = TRUE) 2 | { 3 | ## index processing 4 | my.unique <- function(x) { 5 | ix <- MATCH(x, x) == seq_len(length(x)) 6 | x[ix] 7 | } 8 | if(is.function(by)) by <- by(index(x)) 9 | if(!is.list(by)) by <- list(by) 10 | 11 | ## sanity checks and option processing 12 | stopifnot(length(time(x)) == length(by[[1]])) 13 | if(is.null(frequency)) { 14 | if(is.null(regular)) regular <- inherits(x, "zooreg") 15 | } else { 16 | if(identical(regular, FALSE)) warning(paste(sQuote("regular"), "is ignored")) 17 | regular <- TRUE 18 | } 19 | 20 | ## aggregate data 21 | by_integer <- list(MATCH(by[[1]], by[[1]])) 22 | if(coredata) { 23 | df <- coredata(x) 24 | } else { 25 | df <- as.data.frame(x) 26 | if(ncol(df) > 1L) { 27 | for(i in 1L:ncol(df)) df[[i]] <- x[, i] 28 | } else { 29 | df[[1L]] <- x 30 | } 31 | } 32 | df <- aggregate(df, by_integer, match.fun(FUN), ...) 33 | if(length(unique(as.character(df[,1]))) == length(df[,1])) 34 | row.names(df) <- df[, 1] 35 | df <- df[, -1] 36 | if(is.matrix(x)) df <- as.matrix(df) 37 | 38 | ## regularity processing, set up return value 39 | ix <- my.unique(by[[1]]) 40 | rval <- zoo(df, ix[!is.na(ix)]) 41 | 42 | if(regular) { 43 | freq <- ifelse(is.null(frequency), frequency(rval), frequency) 44 | rval <- zoo(df, ix, freq) 45 | } 46 | 47 | return(rval) 48 | } 49 | 50 | # works even if zoo series has duplicates among its times 51 | split.zoo <- function(x, f, drop = FALSE, ...) { 52 | ix <- time(x) 53 | xc <- coredata(x) 54 | if (length(dim(xc)) < 2) { 55 | lapply(split(seq_along(xc), f, drop = drop, ...), 56 | function(ind) zoo(xc[ind], ix[ind])) 57 | } else { 58 | lapply(split(seq_len(nrow(xc)), f, drop = drop, ...), 59 | function(ind) zoo(xc[ind, , drop = drop], ix[ind])) 60 | } 61 | } 62 | 63 | 64 | -------------------------------------------------------------------------------- /R/as.Date.R: -------------------------------------------------------------------------------- 1 | as.Date <- function (x, ...) { 2 | ## for plain numeric input, call zoo:::as.Date.numeric 3 | if (!is.object(x) && is.numeric(x)) as.Date.numeric(x, ...) 4 | else UseMethod("as.Date") 5 | } 6 | 7 | as.Date.numeric <- function (x, origin, ...) { 8 | if (missing(origin)) origin <- "1970-01-01" 9 | if (identical(origin, "0000-00-00")) origin <- as.Date("0000-01-01", ...) - 1 10 | as.Date(origin, ...) + x 11 | } 12 | 13 | .as_Date_default <- function(x, ...) base::as.Date(x, ...) 14 | -------------------------------------------------------------------------------- /R/as.Date.ts.R: -------------------------------------------------------------------------------- 1 | # as.Date.numeric <- function (x, origin = "1970-01-01", ...) 2 | # as.Date(origin, ...) + x 3 | 4 | as.Date.ts <- function(x, offset = 0, ...) { 5 | time.x <- unclass(time(x)) + offset 6 | if (frequency(x) == 1) 7 | as.Date(paste(time.x, 1, 1, sep = "-")) 8 | else if (frequency(x) == 4) 9 | as.Date(paste((time.x + .001) %/% 1, 3*(cycle(x)-1)+1, 1, sep = "-")) 10 | else if (frequency(x) == 12) 11 | as.Date(paste((time.x + .001) %/% 1, cycle(x), 1, sep = "-")) 12 | else 13 | stop("unable to convert ts time to Date class") 14 | } 15 | 16 | -------------------------------------------------------------------------------- /R/as.zoo.R: -------------------------------------------------------------------------------- 1 | as.zoo <- function(x, ...) 2 | { 3 | UseMethod("as.zoo") 4 | } 5 | 6 | as.zoo.default <- function(x, ...) 7 | { 8 | zoo(structure(x, dim = dim(x)), index(x), ...) 9 | } 10 | 11 | as.zoo.factor <- function(x, ...) 12 | { 13 | zoo(x, ...) 14 | } 15 | 16 | as.zoo.matrix <- function(x, ...) 17 | { 18 | zoo(x, ...) 19 | } 20 | 21 | as.zoo.data.frame <- function(x, ...) 22 | { 23 | zoo(as.matrix(x), ...) 24 | } 25 | 26 | as.zoo.fts <- function(x, ...) 27 | { 28 | zoo(as.matrix(x), attr(x, "dates")) 29 | } 30 | 31 | as.zoo.irts <- function(x, ...) 32 | { 33 | zoo(x$value, x$time, ...) 34 | } 35 | 36 | as.zoo.its <- function(x, ...) 37 | { 38 | index <- attr(x, "dates") 39 | class(x) <- attr(x, "dates") <- NULL 40 | zoo(x, index, ...) 41 | } 42 | 43 | # as.mcmc.default can handle other direction 44 | as.zoo.mcmc <- function(x, ...) 45 | { 46 | as.zoo(as.ts(x, ...)) 47 | } 48 | 49 | as.zoo.timeSeries <- function(x, ...) { 50 | zoo(as.matrix(x), timeSeries::time(x), ...) 51 | } 52 | 53 | as.zoo.xts <- function(x, ...) { 54 | y <- coredata(x) 55 | if (is.null(dim(y)) && length(y) == 0) { 56 | y <- NULL 57 | } 58 | zoo(y, order.by = index(x), ...) 59 | } 60 | 61 | as.zooreg.xts <- function(x, frequency = NULL, ...) { 62 | as.zooreg(as.zoo(x, ...), frequency = frequency) 63 | } 64 | 65 | as.zoo.zoo <- function(x, ...) x 66 | 67 | as.vector.zoo <- function(x, mode = "any") 68 | as.vector(coredata(x), mode = mode) 69 | 70 | as.matrix.zoo <- function(x, ...) 71 | { 72 | y <- as.matrix(coredata(x), ...) 73 | if (identical(coredata(x), numeric(0))) dim (y) <- c(0, 0) 74 | if (length(y) > 0) { 75 | colnames(y) <- if (length(colnames(x)) > 0) 76 | colnames(x) 77 | else { 78 | lab <- deparse(substitute(x), width.cutoff = 100L, nlines = 1L) 79 | if (NCOL(x) == 1) 80 | lab 81 | else paste(lab, 1:NCOL(x), sep = ".") 82 | } 83 | } else if (nrow(y) != length(index(x))) { 84 | dim(y) <- c(length(index(x)), 0) 85 | } 86 | if (!is.null(y) && nrow(y) > 0 && is.null(row.names(y))) 87 | row.names(y) <- index2char(index(x), frequency = attr(x, "frequency")) 88 | return(y) 89 | } 90 | 91 | as.data.frame.zoo <- function(x, row.names = NULL, optional = FALSE, ...) 92 | { 93 | y <- as.data.frame(coredata(x), optional = optional, ...) 94 | if(NCOL(x) > 0 && !optional) { 95 | colnames(y) <- if (length(colnames(x)) > 0) 96 | colnames(x) 97 | else { 98 | lab <- deparse(substitute(x), width.cutoff = 100L, nlines = 1L) 99 | if (NCOL(x) == 1) lab 100 | else paste(lab, 1:NCOL(x), sep = ".") 101 | } 102 | } 103 | if (!is.null(row.names)) row.names(y) <- row.names 104 | else { 105 | tmp <- index2char(index(x), frequency = attr(x, "frequency")) 106 | if (NROW(y) > 0 && !any(duplicated(tmp))) row.names(y) <- tmp 107 | } 108 | return(y) 109 | } 110 | 111 | as.list.zoo <- function(x, ...) { 112 | if (length(dim(x)) == 0) list(x) 113 | else lapply(as.data.frame(x), zoo, index(x), attr(x, "frequency")) 114 | } 115 | 116 | as.list.ts <- function(x, ...) { 117 | if (is.matrix(x)) 118 | lapply(as.data.frame(x), ts, 119 | start = start(x), end = end(x), freq = frequency(x)) 120 | else 121 | list(x) 122 | } 123 | 124 | 125 | ## regular series coercions 126 | 127 | as.zooreg <- function(x, frequency = NULL, ...) 128 | { 129 | UseMethod("as.zooreg") 130 | } 131 | 132 | as.zooreg.default <- function(x, frequency = NULL, ...) 133 | { 134 | as.zooreg(as.zoo(x, ...), frequency = frequency) 135 | } 136 | 137 | as.zooreg.ts <- as.zoo.ts <- function(x, frequency = NULL, ...) 138 | { 139 | xtsp <- tsp(x) 140 | if(is.null(frequency)) frequency <- xtsp[3] 141 | zooreg(coredata(x), start = xtsp[1], end = xtsp[2], frequency = frequency, ...) 142 | } 143 | 144 | as.ts.zooreg <- function(x, ...) 145 | { 146 | freq <- frequency(x) 147 | deltat <- 1/freq 148 | tt <- as.numeric(time(x)) 149 | round. <- if(isTRUE(all.equal(c(deltat, tt), round(c(deltat, tt))))) { 150 | function(x) floor(x + 0.5) 151 | } else { 152 | function(x) deltat * floor(x/deltat + 0.5) 153 | } 154 | tt <- round.(tt) 155 | tt2 <- round.(seq(head(tt,1), tail(tt,1), deltat)) 156 | fill <- list(...)$fill 157 | if(is.null(fill)) fill <- NA 158 | xx <- merge(zoo(coredata(x), tt), zoo(, tt2), fill = fill) 159 | ts(coredata(xx), start = tt[1], frequency = freq) 160 | } 161 | 162 | as.ts.zoo <- function(x, ...) 163 | { 164 | if(is.regular(x)) { 165 | attr(x, "frequency") <- frequency(x) 166 | return(as.ts.zooreg(x, ...)) 167 | } else { 168 | warning(paste(sQuote("x"), "does not have an underlying regularity")) 169 | return(ts(coredata(x))) 170 | } 171 | } 172 | 173 | as.zoo.zooreg <- function(x, ...) { 174 | attr(x, "frequency") <- NULL 175 | class(x) <- "zoo" 176 | return(x) 177 | } 178 | 179 | as.zooreg.zoo <- function(x, frequency = NULL, ...) 180 | { 181 | if(!is.null(frequency)) { 182 | frequency(x) <- frequency 183 | } else { 184 | freq <- frequency(x) 185 | if(!is.null(freq)) { 186 | attr(x, "frequency") <- freq 187 | class(x) <- c("zooreg", "zoo") 188 | } else { 189 | warning(paste(sQuote("x"), "does not have an underlying regularity")) 190 | x <- zooreg(coredata(x)) 191 | } 192 | } 193 | return(x) 194 | } 195 | -------------------------------------------------------------------------------- /R/as.zoo.tis.R: -------------------------------------------------------------------------------- 1 | as.zoo.tis <- function(x, class = "ti", ...) { 2 | if (class == "ti") { 3 | as.zoo(as.zooreg(x, class = "ti", ...)) 4 | } else if (class == "numeric") { 5 | zoo(tis::stripTis(x), time(tis::ti(x), offset = 0)) 6 | } else { 7 | asFun <- paste("as", class, sep = ".") 8 | zoo(tis::stripTis(x), do.call(asFun, list(tis::POSIXct(tis::ti(x), offset = 0, tz = "GMT"))), ...) 9 | } 10 | } 11 | 12 | as.zooreg.tis <- function(x, frequency = NULL, class = "ti", ...) { 13 | if (class == "ti") zooreg(tis::stripTis(x), start = start(x), ...) 14 | else as.zooreg(as.zoo(x, class = class, ...), frequency = frequency) 15 | } 16 | 17 | -------------------------------------------------------------------------------- /R/barplot.zoo.R: -------------------------------------------------------------------------------- 1 | barplot.zoo <- function(height, names.arg = NULL, ...) 2 | { 3 | x <- coredata(height) 4 | if(!is.null(dim(x))) x <- t(x) 5 | if(is.null(names.arg)) names.arg <- index2char(index(height)) 6 | barplot(x, names.arg = names.arg, ...) 7 | } 8 | 9 | boxplot.zoo <- function(x, ...) boxplot(coredata(x), ...) 10 | -------------------------------------------------------------------------------- /R/coredata.R: -------------------------------------------------------------------------------- 1 | coredata <- function(x, ...) 2 | UseMethod("coredata") 3 | 4 | coredata.default <- function(x, ...) x 5 | 6 | coredata.zoo <- function(x, ...) 7 | { 8 | attr(x, "class") <- attr(x, "oclass") 9 | attr(x, "index") <- attr(x, "oclass") <- attr(x, "frequency") <- NULL 10 | return(x) 11 | } 12 | 13 | ## # experimental coredata.zoo to take advantage of new C code contributed from xts 14 | ## .coredata.zoo <- function(x, ...) { 15 | ## if(length(x) == 0) 16 | ## return(vector(storage.mode(x))) 17 | ## .Call("zoo_coredata", x, TRUE, PACKAGE = "zoo") # second arg is to copy most attr, for compat with xts 18 | ## } 19 | 20 | coredata.ts <- function(x, ...) 21 | { 22 | x <- unclass(x) 23 | attr(x, "tsp") <- NULL 24 | return(x) 25 | } 26 | 27 | coredata.irts <- function(x, ...) 28 | { 29 | return(x$value) 30 | } 31 | 32 | coredata.its <- function(x, ...) 33 | { 34 | return(x@.Data) 35 | } 36 | 37 | 38 | "coredata<-" <- function(x, value) 39 | { 40 | UseMethod("coredata<-") 41 | } 42 | 43 | "coredata<-.zoo" <- function(x, value) 44 | { 45 | stopifnot(length(x) == length(value)) 46 | if(!(is.vector(value) || is.factor(value) || is.matrix(value) || is.data.frame(value))) 47 | stop(paste(dQuote("value"), ": attempt to assign invalid coredata to zoo object")) 48 | if(is.matrix(value) || is.data.frame(value)) value <- as.matrix(value) 49 | 50 | x[] <- value 51 | attr(x, "oclass") <- attr(value, "class") 52 | return(x) 53 | } 54 | 55 | "coredata<-.ts" <- function(x, value) 56 | { 57 | stopifnot(length(x) == length(value)) 58 | dim(value) <- dim(x) 59 | x[] <- value 60 | return(x) 61 | } 62 | 63 | "coredata<-.irts" <- function(x, value) 64 | { 65 | stopifnot(length(x$value) == length(value)) 66 | dim(value) <- dim(x$value) 67 | x$value[] <- value 68 | return(x) 69 | } 70 | 71 | "coredata<-.its" <- function(x, value) 72 | { 73 | stopifnot(length(x@.Data) == length(value)) 74 | dim(value) <- dim(x@.Data) 75 | x@.Data[] <- as.matrix(value) 76 | return(x) 77 | } 78 | -------------------------------------------------------------------------------- /R/ggplot2.zoo.R: -------------------------------------------------------------------------------- 1 | fortify.zoo <- function(model, data, names = c("Index", "Series", "Value"), 2 | melt = FALSE, sep = NULL, ...) 3 | { 4 | if (!is.null(sep) && !melt) stop("Cannot specify sep if melt = FALSE") 5 | ## dimensions 6 | n <- NROW(model) 7 | k <- NCOL(model) 8 | 9 | ## dots only named data.frame arguments 10 | dots <- list(...) 11 | dots <- dots[names(dots) %in% 12 | c("row.names", "check.rows", "check.names", "fix.empty.names", "stringsAsFactors")] 13 | 14 | ## series labels 15 | lab <- colnames(model) 16 | if(is.null(lab)) lab <- rep.int(deparse(substitute(model)), k) 17 | lab <- make.unique(lab) 18 | 19 | ## return data names 20 | nm <- c("Index", "Series", "Value") 21 | if(!is.null(names(names))) names <- names[nm] 22 | if(is.list(names)) { 23 | names(names) <- nm 24 | for(i in 1L:3L) if(is.null(names[[i]]) || anyNA(names[[i]])) names[[i]] <- nm[i] 25 | nm <- unlist(names) 26 | } else { 27 | names <- rep_len(names, 3L) 28 | nm[!is.na(names)] <- names[!is.na(names)] 29 | } 30 | 31 | ## either long format (melt = TRUE) or wide format (melt = FALSE) 32 | if(melt) { 33 | df <- if(k == 1L) { 34 | do.call("data.frame", c( 35 | list(index(model), factor(rep.int(1, n), labels = lab), coredata(model)), 36 | dots)) 37 | } else { 38 | do.call("data.frame", c( 39 | list(index(model)[rep.int(1:n, k)], 40 | factor(rep(1:k, each = n), levels = 1:k, labels = lab), 41 | as.vector(coredata(model))), 42 | dots)) 43 | } 44 | if (!is.null(sep)) { 45 | df <- data.frame(df[1L], 46 | do.call("rbind", strsplit(as.character(df[[2L]]), ".", fixed = TRUE)), 47 | df[3L]) 48 | } 49 | nl <- length(nm) 50 | names(df) <- c(nm[1L], make.unique(rep_len(nm[-c(1L, nl)], ncol(df) - 2L)), nm[nl]) 51 | } else { 52 | df <- cbind( 53 | do.call("data.frame", c(list(index(model)), dots)), 54 | coredata(model)) 55 | names(df) <- c(nm[1L], lab) 56 | } 57 | 58 | return(df) 59 | } 60 | 61 | 62 | autoplot.zoo <- function(object, geom = "line", facets, ...) 63 | { 64 | ## convert to data.frame (and assure correct label 65 | ## processing by fortify.zoo) 66 | lab <- deparse(substitute(object)) 67 | if(NCOL(object) == 1L) { 68 | if(is.null(dim(object))) dim(object) <- c(NROW(object), 1L) 69 | if(is.null(colnames(object))) colnames(object) <- lab 70 | } 71 | if(is.null(colnames(object))) colnames(object) <- paste(lab, 1:NCOL(object), sep = ".") 72 | df <- fortify.zoo(object, melt = TRUE) 73 | 74 | ## default for facets 75 | single <- nlevels(df$Series) == 1L 76 | if(missing(facets)) { 77 | auto <- TRUE 78 | facets <- if(single) NULL else Series ~ . 79 | } else { 80 | auto <- FALSE 81 | } 82 | 83 | ## process defaults as for old qplot-based interface 84 | if(is.character(geom)) geom <- get(paste0("geom_", geom), asNamespace("ggplot2")) 85 | if(inherits(facets, "formula")) facets <- ggplot2::facet_grid(facets) 86 | 87 | ## "fake" variables for nonstandard evaluation 88 | Index <- Value <- Series <- NULL 89 | 90 | ## call qplot 91 | gg <- if(single | (!is.null(facets) & auto)) { 92 | ggplot2::ggplot(df, ggplot2::aes(x = Index, y = Value, ...)) + geom() + facets + ggplot2::ylab(if(single) levels(df$Series) else "") + ggplot2::xlab("Index") 93 | } else { 94 | ggplot2::ggplot(df, ggplot2::aes(x = Index, y = Value, group = Series, colour = Series, ...)) + geom() + facets + ggplot2::ylab("") + ggplot2::xlab("Index") 95 | } 96 | return(gg) 97 | } 98 | 99 | facet_free <- function (facets = Series ~ ., margins = FALSE, scales = "free_y", ...) { 100 | ggplot2::facet_grid(facets, margins = margins, scales = scales, ...) 101 | } 102 | 103 | yearmon_trans <- function(format = "%b %Y", n = 5) { 104 | breaks. <- function(x) as.yearmon(scales::pretty_breaks(n)(x)) 105 | format. <- function(x) format(x, format = format) 106 | scales::trans_new("yearmon", transform = as.numeric, inverse = as.yearmon, 107 | breaks = breaks., format = format.) 108 | } 109 | 110 | scale_x_yearmon <- function(..., format = "%b %Y", n = 5) { 111 | ggplot2::scale_x_continuous(..., transform = yearmon_trans(format, n)) 112 | } 113 | scale_y_yearmon <- function(..., format = "%b %Y", n = 5) { 114 | ggplot2::scale_y_continuous(..., transform = yearmon_trans(format, n)) 115 | } 116 | 117 | yearqtr_trans <- function(format = "%Y-%q", n = 5) { 118 | breaks. <- function(x) as.yearqtr(scales::pretty_breaks(n)(x)) 119 | format. <- function(x) zoo::format.yearqtr(x, format = format) 120 | scales::trans_new("yearqtr", transform = as.numeric, inverse = as.yearqtr, 121 | breaks = breaks., format = format.) 122 | } 123 | 124 | scale_x_yearqtr <- function(..., format = "%Y-%q", n = 5) { 125 | ggplot2::scale_x_continuous(..., transform = yearqtr_trans(format, n)) 126 | } 127 | scale_y_yearqtr <- function(..., format = "%Y-%q", n = 5) { 128 | ggplot2::scale_y_continuous(..., transform = yearqtr_trans(format, n)) 129 | } 130 | 131 | scale_type.yearqtr <- function(x) c("yearqtr", "continuous") 132 | 133 | scale_type.yearmon <- function(x) c("yearmon", "continuous") 134 | -------------------------------------------------------------------------------- /R/index.R: -------------------------------------------------------------------------------- 1 | index <- function(x, ...) 2 | { 3 | UseMethod("index") 4 | } 5 | 6 | index.default <- function(x, ...) 7 | { 8 | seq_len(NROW(x)) 9 | } 10 | 11 | index.zoo <- function(x, ...) 12 | { 13 | attr(x, "index") 14 | } 15 | 16 | index.ts <- function(x, ...) 17 | { 18 | xtsp <- tsp(x) 19 | seq(xtsp[1], xtsp[2], by = 1/xtsp[3]) 20 | } 21 | 22 | time.zoo <- function(x, ...) 23 | { 24 | index(x) 25 | } 26 | 27 | "index<-" <- function(x, value) 28 | { 29 | UseMethod("index<-") 30 | } 31 | 32 | "time<-" <- function(x, value) 33 | { 34 | UseMethod("time<-") 35 | } 36 | 37 | "index<-.zoo" <- function(x, value) 38 | { 39 | if(length(index(x)) != length(value)) 40 | stop("length of index vectors does not match") 41 | if(is.unsorted(ORDER(value))) 42 | stop("new index needs to be sorted") 43 | attr(x, "index") <- value 44 | return(x) 45 | } 46 | 47 | "time<-.zooreg" <- "index<-.zooreg" <- function(x, value) 48 | { 49 | if(length(index(x)) != length(value)) 50 | stop("length of index vectors does not match") 51 | if(is.unsorted(ORDER(value))) 52 | stop("new index needs to be sorted") 53 | 54 | ## check whether new index still conforms with 55 | ## frequency, if not: drop frequency 56 | d <- try(diff(as.numeric(value)), silent = TRUE) 57 | ok <- if(inherits(d, "try-error") || length(d) < 1 || anyNA(d)) FALSE 58 | else { 59 | deltat <- min(d) 60 | dd <- d/deltat 61 | if(identical(all.equal(dd, round(dd)), TRUE)) { 62 | freq <- 1/deltat 63 | if(freq > 1 && identical(all.equal(freq, round(freq)), TRUE)) freq <- round(freq) 64 | identical(all.equal(attr(x, "frequency") %% freq, 0), TRUE) 65 | } else { 66 | FALSE 67 | } 68 | } 69 | if(!ok) { 70 | attr(x, "frequency") <- NULL 71 | class(x) <- class(x)[-which(class(x) == "zooreg")] 72 | } 73 | 74 | attr(x, "index") <- value 75 | return(x) 76 | } 77 | 78 | "time<-.zoo" <- function(x, value) 79 | { 80 | if(length(index(x)) != length(value)) 81 | stop("length of time vectors does not match") 82 | attr(x, "index") <- value 83 | return(x) 84 | } 85 | 86 | start.zoo <- function(x, ...) 87 | { 88 | if (length(index(x)) > 0) index(x)[1] 89 | else NULL 90 | } 91 | 92 | end.zoo <- function(x, ...) 93 | { 94 | lx <- length(index(x)) 95 | if (lx > 0) index(x)[lx] 96 | else NULL 97 | } 98 | -------------------------------------------------------------------------------- /R/index2char.R: -------------------------------------------------------------------------------- 1 | index2char <- function(x, ...) UseMethod("index2char") 2 | 3 | index2char.default <- function(x, ...) as.character(x) 4 | 5 | index2char.POSIXt <- function(x, ...) format(x, ...) 6 | 7 | index2char.numeric <- function(x, frequency = NULL, digits = getOption("digits") - 3, ...) 8 | { 9 | freq <- frequency 10 | if(is.null(freq)) return(as.character(round(x, digits = digits))) 11 | if(length(x) < 1) return(character(0)) 12 | d <- diff(x) 13 | if(freq > 1 && identical(all.equal(freq, round(freq)), TRUE)) freq <- round(freq) 14 | if(identical(all.equal(freq*d, round(freq*d)), TRUE)) { 15 | if(freq == 1) return(as.character(round(x))) 16 | else return(paste(floor(x), "(", round((x - floor(x)) * freq) + 1, ")", sep = "")) 17 | } else 18 | return(as.character(round(x, digits = digits))) 19 | } 20 | -------------------------------------------------------------------------------- /R/is.regular.R: -------------------------------------------------------------------------------- 1 | is.regular <- function(x, strict = FALSE) { 2 | UseMethod("is.regular") 3 | } 4 | 5 | is.regular.zoo <- function(x, strict = FALSE) 6 | { 7 | delta <- suppressWarnings(try(diff(as.numeric(index(x))), silent = TRUE)) 8 | if(inherits(delta, "try-error") || anyNA(delta)) FALSE 9 | else if(length(delta) < 1) FALSE 10 | else if(strict) identical(all.equal(delta, rep.int(delta[1], length(delta))), TRUE) 11 | else { 12 | delta <- unique(delta) 13 | rval <- identical(all.equal(delta/min(delta), round(delta/min(delta))), TRUE) 14 | if(!rval && identical(all.equal(delta, round(delta)), TRUE)) rval <- TRUE 15 | rval 16 | } 17 | } 18 | 19 | is.regular.ts <- function(x, strict = FALSE) TRUE 20 | 21 | is.regular.zooreg <- function(x, strict = FALSE) 22 | { 23 | if(strict) is.regular.zoo(x, strict = TRUE) else TRUE 24 | } 25 | 26 | is.regular.default <- function(x, strict = FALSE) { 27 | is.regular(as.zoo(x), strict = strict) 28 | } 29 | 30 | frequency.zooreg <- function(x, ...) 31 | { 32 | attr(x, "frequency") 33 | } 34 | 35 | frequency.zoo <- function(x, ...) 36 | { 37 | ## check whether frequency is available 38 | freq <- attr(x, "frequency") 39 | if(!is.null(freq) || length(index(x)) < 2) return(freq) 40 | 41 | ## check regularity 42 | delta <- suppressWarnings(try(diff(as.numeric(index(x))), silent = TRUE)) 43 | reg <- if(inherits(delta, "try-error") || anyNA(delta)) FALSE 44 | else { 45 | delta <- unique(delta) 46 | rval <- identical(all.equal(delta/min(delta), round(delta/min(delta))), TRUE) 47 | if(rval) freq <- 1/min(delta) 48 | else if(identical(all.equal(delta, round(delta)), TRUE)) { 49 | ## special case: integer indexes 50 | ## get frequency as greatest common divisor (of differences) 51 | gcd <- function(x) { 52 | gcd0 <- function(a, b) ifelse(b==0 | a==b, a, gcd0(b, a %% b)) 53 | if(length(x) < 2) x <- c(x, as.integer(0)) 54 | if(length(x) < 3) { 55 | return(gcd0(x[1], x[2])) 56 | } else { 57 | x <- sapply(1:(length(x) - 1), function(i) gcd0(x[i], x[i+1])) 58 | gcd(x) 59 | } 60 | } 61 | freq <- 1/gcd(delta) 62 | rval <- TRUE 63 | } 64 | rval 65 | } 66 | if(!reg) return(NULL) 67 | if(freq > 1 && identical(all.equal(freq, round(freq)), TRUE)) freq <- round(freq) 68 | return(freq) 69 | } 70 | 71 | "frequency<-" <- function(x, value) 72 | UseMethod("frequency<-") 73 | 74 | "frequency<-.zoo" <- function(x, value) { 75 | delta <- suppressWarnings(try(diff(as.numeric(index(x))), silent = TRUE)) 76 | freqOK <- if(inherits(delta, "try-error") || anyNA(delta)) FALSE 77 | else if(length(delta) < 1) TRUE 78 | else identical(all.equal(delta*value, round(delta*value)), TRUE) 79 | stopifnot(freqOK) 80 | if(value > 1 && identical(all.equal(value, round(value)), TRUE)) value <- round(value) 81 | attr(x, "frequency") <- value 82 | class(x) <- c("zooreg", "zoo") 83 | return(x) 84 | } 85 | 86 | "frequency<-.zooreg" <- function(x, value) { 87 | delta <- diff(as.numeric(index(x))) 88 | stopifnot(identical(all.equal(delta*value, round(delta*value)), TRUE)) 89 | attr(x, "frequency") <- value 90 | return(x) 91 | } 92 | 93 | deltat.zoo <- function(x, ...) 94 | { 95 | rval <- frequency.zoo(x, ...) 96 | if(is.null(rval)) NULL else 1/rval 97 | } 98 | 99 | deltat.zooreg <- function(x, ...) 100 | { 101 | 1/frequency.zooreg(x, ...) 102 | } 103 | 104 | cycle.zooreg <- function(x, ...) 105 | { 106 | freq <- frequency(x) 107 | ix <- as.numeric(index(x)) 108 | d <- diff(ix) 109 | if(!identical(all.equal(freq*d, round(freq*d)), TRUE)) 110 | stop(paste(sQuote("cycle"), "not available for", sQuote("x"))) 111 | return(zoo(round((ix - floor(ix)) * freq) + 1, order.by = index(x), freq)) 112 | } 113 | 114 | cycle.zoo <- function(x, ...) 115 | { 116 | if(is.regular(x)) cycle.zooreg(x) 117 | else stop(sQuote("x"), "is not regular") 118 | } 119 | -------------------------------------------------------------------------------- /R/na.StructTS.R: -------------------------------------------------------------------------------- 1 | 2 | na.StructTS <- function(object, ...) UseMethod("na.StructTS") 3 | 4 | na.StructTS.ts <- function(object, ..., na.rm = FALSE, maxgap = Inf) 5 | { 6 | na.StructTS.0 <- function(y) { 7 | yf <- y 8 | isna <- is.na(y) 9 | yf[isna] <- rowSums(tsSmooth(StructTS(y))[,-2])[isna] 10 | .fill_short_gaps(y, yf, maxgap = maxgap) 11 | } 12 | object[] <- if (length(dim(object)) == 0) na.StructTS.0(object) 13 | else apply(object, 2, na.StructTS.0) 14 | if (na.rm) na.trim(object, is.na = "all") else object 15 | } 16 | 17 | na.StructTS.zoo <- function(object, ..., na.rm = FALSE, maxgap = Inf) { 18 | z <- na.StructTS(as.ts(object), ..., na.rm = FALSE, maxgap = maxgap) 19 | z <- as.zoo(z) 20 | time(z) <- time(object) 21 | if (na.rm) na.trim(z, is.na = "all") else z 22 | } 23 | 24 | -------------------------------------------------------------------------------- /R/na.aggregate.R: -------------------------------------------------------------------------------- 1 | na.aggregate <- function(object, ...) UseMethod("na.aggregate") 2 | 3 | ## fills NA values with some aggregated function of the data. 4 | ## generalises imputing by the overall mean, by calendar month, etc. 5 | na.aggregate.default <- function(object, by = 1, ..., FUN = mean, na.rm = FALSE, maxgap = Inf) 6 | { 7 | if (is.function(by)) by <- by(time(object), ...) 8 | ## applied to each aggregated group in each series: 9 | f <- function(x) 10 | replace(x, is.na(x), FUN(x[!is.na(x)])) 11 | na.aggregate.0 <- function(y) { 12 | yf <- ave(y, by, FUN = f) 13 | .fill_short_gaps(y, yf, maxgap = maxgap) 14 | } 15 | object[] <- if (length(dim(object)) == 0) na.aggregate.0(object) 16 | else apply(object, 2, na.aggregate.0) 17 | if (na.rm) na.trim(object, is.na = "all") else object 18 | } 19 | -------------------------------------------------------------------------------- /R/na.approx.R: -------------------------------------------------------------------------------- 1 | na.approx <- function(object, ...) UseMethod("na.approx") 2 | 3 | na.approx.zoo <- function(object, x = index(object), xout, ..., na.rm = TRUE, maxgap = Inf, along) { 4 | 5 | if (!missing(along)) { 6 | warning("along to be deprecated - use x instead") 7 | if (missing(x)) x <- along 8 | } 9 | 10 | missing.xout <- missing(xout) || is.null(xout) 11 | if (is.function(x)) x <- x(index(object)) 12 | if (!missing.xout && is.function(xout)) xout <- xout(index(object)) 13 | order.by <- if (missing.xout) index(object) else xout 14 | xout <- if (missing.xout) x else xout 15 | 16 | if (missing.xout || identical(xout, index(object))) { 17 | result <- object 18 | } else { 19 | object.x <- object 20 | if (!identical(class(x), class(xout))) { 21 | index(object.x) <- as.numeric(x) 22 | xout <- as.numeric(xout) 23 | } else { 24 | index(object.x) <- x 25 | } 26 | objectm <- merge(object.x, zoo(, xout)) 27 | if (length(dim(objectm)) == 2) colnames(objectm) <- colnames(object) 28 | result <- window(objectm, index. = xout) 29 | } 30 | result[] <- na.approx.default(object, x = x, xout = xout, na.rm = FALSE, ..., maxgap = maxgap) 31 | if ((!missing(order.by) && !is.null(order.by)) || !missing.xout) { 32 | index(result) <- order.by 33 | } 34 | 35 | if (na.rm) { 36 | result <- na.trim(result, is.na = "all", maxgap = maxgap) 37 | } 38 | 39 | result 40 | 41 | } 42 | 43 | na.approx.zooreg <- function(object, ...) { 44 | object. <- structure(object, class = setdiff(class(object), "zooreg")) 45 | as.zooreg(na.approx(object., ...)) 46 | } 47 | 48 | 49 | na.approx.default <- function(object, x = index(object), xout = x, ..., na.rm = TRUE, maxgap = Inf, along) { 50 | 51 | if (!missing(along)) { 52 | warning("along to be deprecated - use x instead") 53 | if (missing(x)) x <- along 54 | } 55 | 56 | na.approx.vec <- function(x, y, xout = x, ...) { 57 | na <- is.na(y) 58 | if(sum(!na) < 2L) { 59 | ## approx() cannot be applied here, hence simply: 60 | yf <- rep.int(NA, length(xout)) 61 | mode(yf) <- mode(y) 62 | if(any(!na)) { 63 | if(x[!na] %in% xout) { 64 | yf[xout == x[!na]] <- y[!na] 65 | } 66 | } 67 | return(yf) 68 | } 69 | if(all(!na) && (length(xout) > maxgap) && !all(xout %in% x)) { 70 | ## for maxgap to work correctly 'y' has to contain 71 | ## actual NAs and be expanded to the full x-index 72 | xf <- sort(unique(c(x, xout))) 73 | yf <- rep.int(NA, length(xf)) 74 | yf[MATCH(x, xf)] <- y 75 | x <- xf 76 | y <- yf 77 | } 78 | yf <- approx(x[!na], y[!na], xout, ...)$y 79 | if (maxgap < length(y)) { 80 | ## construct a series like y but with only gaps > maxgap 81 | ## (actual values don't matter as we only use is.na(ygap) below) 82 | ygap <- .fill_short_gaps(y, seq_along(y), maxgap = maxgap) 83 | ## construct y values at 'xout', keeping NAs from ygap 84 | ## (using indexing, as approx() does not allow NAs to be propagated) 85 | ix <- approx(x, seq_along(y), xout, ...)$y 86 | yx <- ifelse(is.na(ygap[floor(ix)] + ygap[ceiling(ix)]), NA, yf) 87 | yx 88 | } else { 89 | yf 90 | } 91 | } 92 | 93 | if (!identical(length(x), length(index(object)))) { 94 | stop("x and index must have the same length") 95 | } 96 | x. <- as.numeric(x) 97 | if (missing(xout) || is.null(xout)) xout <- x. 98 | xout. <- as.numeric(xout) 99 | object. <- coredata(object) 100 | 101 | result <- if (length(dim(object.)) < 2) { 102 | na.approx.vec(x., coredata(object.), xout = xout., ...) 103 | } else { 104 | apply(coredata(object.), 2, na.approx.vec, x = x., xout = xout., ...) 105 | } 106 | 107 | if (na.rm) { 108 | result <- na.trim(result, is.na = "all", maxgap = maxgap) 109 | } 110 | 111 | result 112 | 113 | } 114 | 115 | na.approx.ts <- function(object, ...) { 116 | as.ts(na.approx(as.zoo(object), ...)) 117 | } 118 | 119 | ## x = series with gaps 120 | ## fill = same series with filled gaps 121 | .fill_short_gaps <- function(x, fill, maxgap) { 122 | if (maxgap <= 0) 123 | return(x) 124 | if (maxgap >= length(x)) 125 | return(fill) 126 | naruns <- rle(is.na(x)) 127 | naruns$values[naruns$lengths > maxgap] <- FALSE 128 | naok <- inverse.rle(naruns) 129 | x[naok] <- fill[naok] 130 | return(x) 131 | } 132 | -------------------------------------------------------------------------------- /R/na.fill.R: -------------------------------------------------------------------------------- 1 | 2 | # fill is a 3 component list or is coerced to one representing 3 | # fill char to left of leftmost non-NA, fill character to interior NAs 4 | # and fill char to right of rightmost non-NA 5 | # If component is "extend" then left or rightmost NA is extended or interior 6 | # NA is linearly interpolated 7 | # If component is NULL then the corresponding NA is dropped. 8 | 9 | na.fill0 <- function(object, fill, ix = !is.na(object)) 10 | { 11 | if (length(object) == 0L) { 12 | object 13 | } else if (length(fill) == 0L || sum(lengths(as.list(fill))) == 0L) { 14 | structure(object[ix], na.action = which(!ix)) 15 | } else if (length(fill) == 1L) { 16 | if (identical(as.list(fill)[[1L]], "extend")) 17 | stop("fill cannot be 'extend'") 18 | if (!is.logical(ix)) ix <- seq_along(object) %in% ix 19 | replace(object, !ix, as.list(fill)[[1L]]) 20 | } else { 21 | fill <- rep(as.list(fill), length = 3L) 22 | if (identical(fill[[2L]], "extend")) 23 | stop("fill[[2L]] cannot be 'extend'") 24 | ix <- if (is.logical(ix)) rep(ix, length = length(object)) else seq_along(object) %in% ix 25 | wx <- which(ix) 26 | if (length(wx) == 0L) { 27 | object[] <- fill[[2L]] 28 | object 29 | } else { 30 | rng <- range(wx) 31 | 32 | if (identical(fill[[1L]], "extend")) fill[[1L]] <- object[rng[1L]] 33 | if (identical(fill[[3L]], "extend")) fill[[3L]] <- object[rng[2L]] 34 | 35 | fill_lens <- lengths(fill) 36 | 37 | pre <- seq_along(ix) < rng[1L] 38 | post <- seq_along(ix) > rng[2L] 39 | 40 | if (fill_lens[2L]) object[!ix] <- fill[[2L]] 41 | if (fill_lens[1L]) object[pre] <- fill[[1L]] 42 | if (fill_lens[3L]) object[post] <- fill[[3L]] 43 | 44 | omit <- (pre & !fill_lens[1L]) | 45 | (!pre & !post & !ix & !fill_lens[2L]) | 46 | (post & !fill_lens[3L]) 47 | object <- object[!omit] 48 | if (sum(omit)) structure(object, na.action = which(omit)) else object 49 | } 50 | } 51 | } 52 | 53 | na.fill <- function(object, fill, ...) UseMethod("na.fill") 54 | 55 | na.fill.zoo <- function(object, fill, ix, ...) { 56 | 57 | if (length(dim(object)) == 2 && NCOL(object) > 1) { 58 | ixmiss <- missing(ix) 59 | L <- lapply(1:NCOL(object), 60 | function(i) { 61 | if (ixmiss) ix <- !is.na(object[,i]) 62 | na.fill(object[,i], fill, ix, ...) 63 | }) 64 | out <- do.call("merge", c(L, all = FALSE)) 65 | colnames(out) <- colnames(object) 66 | return(out) 67 | } 68 | 69 | if (missing(ix)) ix <- !is.na(object) 70 | 71 | if ((is.logical(ix) && any(ix)) || (!is.logical(ix) && length(ix))) { 72 | 73 | n <- length(object) 74 | # integer indexes for output points which are present 75 | wix <- if (is.logical(ix)) which(ix) else ix 76 | # min and max integer index 77 | wx.min <- head(wix, 1) 78 | wx.max <- tail(wix, 1) 79 | # similar to wrng <- wx.min:wx.max 80 | wrng <- seq(wx.min, length.out = wx.max - wx.min + 1) 81 | 82 | # recycle to length 3 83 | fill <- rep(as.list(fill), length.out = 3) 84 | # we will be coercing fill values to the class of coredata(data). 85 | # This allows fill=c("extend", NA) to work even though NA is coerced to 86 | # a character NA. 87 | as.cls <- if (is.integer(coredata(object))) { 88 | as.integer 89 | } else if(is.numeric(coredata(object))) { 90 | as.numeric 91 | } else if(is.character(coredata(object))) { 92 | as.character 93 | } else { 94 | as.logical 95 | } 96 | fill <- lapply(fill, function(x) if (is.character(x) && 97 | pmatch(x, "extend", nomatch = 0)) "extend" else as.cls(x)) 98 | # fill points on left 99 | if (length(fill[[1]]) > 0) 100 | if (!is.null(fill[[1]])) object[seq_len(wx.min - 1)] <- 101 | if (is.character(fill[[1]]) && !is.na(fill[[1]]) && fill[[1]] == "extend") 102 | object[[wx.min]] else fill[[1]] 103 | # fill intermediate points 104 | # - this is for zoo method, for zooreg method it would be possible to 105 | # perform linear interpolation in proportion to time rather than 106 | # in proportion to the integer index 107 | if (length(fill[[2]]) > 0) { 108 | if (is.character(fill[[2]]) && !is.na(fill[[2]]) && fill[[2]] == "extend") object[wrng] <- 109 | # as.list(approx(wix, unlist(object[wix]), xout = wrng)$y) 110 | approx(wix, unlist(object[wix]), xout = wrng)$y 111 | else object[intersect(which(!ix), wrng)] <- fill[[2]] 112 | } 113 | # fill points on right 114 | if (length(fill[[3]]) > 0) 115 | object[seq(wx.max + 1, length.out = n - wx.max)] <- 116 | if (is.character(fill[[3]]) && !is.na(fill[[3]]) && fill[[3]] == "extend") 117 | object[[wx.max]] else fill[[3]] 118 | 119 | keep <- seq_len(n) 120 | if (length(fill[[1]]) == 0) keep <- unique(pmax(wx.min, keep)) 121 | if (length(fill[[2]]) == 0) { 122 | wrng <- seq(wx.min, length.out = wx.max - wx.min + 1) 123 | keep <- setdiff(keep, intersect(which(!ix), wrng)) 124 | } 125 | if (length(fill[[3]]) == 0) keep <- unique(pmin(wx.max, keep)) 126 | return(object[keep, , drop = is.null(dim(object))]) 127 | } else if(length(fill)) { 128 | fill <- unlist(fill[1])[1] 129 | object[is.na(object)] <- if(!is.na(fill) && fill == "extend") NA else fill 130 | return(object) 131 | } 132 | } 133 | 134 | na.fill.default <- function(object, fill, ix, ...) { 135 | coredata(na.fill(zoo(object), fill, ix, ...)) 136 | } 137 | 138 | na.fill.ts <- function(object, fill, ix, ...) { 139 | as.ts(na.fill(as.zoo(object), fill, ix, ...)) 140 | } 141 | 142 | -------------------------------------------------------------------------------- /R/na.locf.R: -------------------------------------------------------------------------------- 1 | na.locf0 <- function(object, fromLast = FALSE, maxgap = Inf, coredata = NULL) { 2 | if(is.null(coredata)) coredata <- inherits(object, "ts") || inherits(object, "zoo") || inherits(object, "its") || inherits(object, "irts") 3 | if(coredata) { 4 | x <- object 5 | object <- if (fromLast) rev(coredata(object)) else coredata(object) 6 | } else { 7 | if(fromLast) object <- rev(object) 8 | } 9 | ok <- which(!is.na(object)) 10 | if(is.na(object[1L])) ok <- c(1L, ok) 11 | gaps <- diff(c(ok, length(object) + 1L)) 12 | object <- if(any(gaps > maxgap)) { 13 | .fill_short_gaps(object, rep(object[ok], gaps), maxgap = maxgap) 14 | } else { 15 | rep(object[ok], gaps) 16 | } 17 | if (fromLast) object <- rev(object) 18 | if(coredata) { 19 | x[] <- object 20 | return(x) 21 | } else { 22 | return(object) 23 | } 24 | } 25 | 26 | na.locf <- function(object, na.rm = TRUE, ...) 27 | UseMethod("na.locf") 28 | 29 | na.locf.default <- function(object, na.rm = TRUE, fromLast, rev, maxgap = Inf, rule = 2, ...) { 30 | 31 | L <- list(...) 32 | if ("x" %in% names(L) || "xout" %in% names(L)) { 33 | 34 | if (!missing(fromLast)) { 35 | stop("fromLast not supported if x or xout is specified") 36 | } 37 | return(na.approx(object, na.rm = na.rm, 38 | maxgap = maxgap, method = "constant", rule = rule, ...)) 39 | } 40 | 41 | if (!missing(rev)) { 42 | warning("na.locf.default: rev= deprecated. Use fromLast= instead.") 43 | if (missing(fromLast)) fromLast <- rev 44 | } else if (missing(fromLast)) fromLast <- FALSE 45 | rev <- base::rev 46 | object[] <- if (length(dim(object)) == 0) 47 | na.locf0(object, fromLast = fromLast, maxgap = maxgap) 48 | else 49 | apply(object, length(dim(object)), na.locf0, fromLast = fromLast, maxgap = maxgap) 50 | if (na.rm) na.trim(object, is.na = "all") else object 51 | } 52 | 53 | na.locf.data.frame <- function(object, na.rm = TRUE, fromLast = FALSE, maxgap = Inf, ...) 54 | { 55 | object[] <- lapply(object, na.locf0, fromLast = fromLast, maxgap = maxgap) 56 | if (na.rm) na.omit(object) else object 57 | } 58 | 59 | 60 | na.contiguous.data.frame <- 61 | na.contiguous.zoo <- function(object, ...) 62 | { 63 | if (length(dim(object)) == 2) 64 | good <- apply(!is.na(object), 1, all) 65 | else good <- !is.na(object) 66 | if (!sum(good)) 67 | stop("all times contain an NA") 68 | tt <- cumsum(!good) 69 | ln <- sapply(0:max(tt), function(i) sum(tt == i)) 70 | seg <- (seq_along(ln)[ln == max(ln)])[1] - 1 71 | keep <- (tt == seg) 72 | st <- min(which(keep)) 73 | if (!good[st]) 74 | st <- st + 1 75 | en <- max(which(keep)) 76 | omit <- integer(0) 77 | n <- NROW(object) 78 | if (st > 1) 79 | omit <- c(omit, 1:(st - 1)) 80 | if (en < n) 81 | omit <- c(omit, (en + 1):n) 82 | cl <- class(object) 83 | if (length(omit)) { 84 | object <- if (length(dim(object))) 85 | object[st:en, ] 86 | else object[st:en] 87 | attr(omit, "class") <- "omit" 88 | attr(object, "na.action") <- omit 89 | if (!is.null(cl)) 90 | class(object) <- cl 91 | } 92 | object 93 | } 94 | 95 | na.contiguous.list <- function(object, ...) 96 | lapply(object, na.contiguous) 97 | -------------------------------------------------------------------------------- /R/na.spline.R: -------------------------------------------------------------------------------- 1 | na.spline <- function(object, ...) UseMethod("na.spline") 2 | 3 | na.spline.zoo <- function(object, x = index(object), xout, ..., na.rm = TRUE, maxgap = Inf, along) { 4 | 5 | if (!missing(along)) { 6 | warning("along to be deprecated - use x instead") 7 | if (missing(x)) x <- along 8 | } 9 | 10 | missing.xout <- missing(xout) || is.null(xout) 11 | if (is.function(x)) x <- x(index(object)) 12 | if (!missing.xout && is.function(xout)) xout <- xout(index(object)) 13 | order.by <- if (missing.xout) index(object) else xout 14 | xout <- if (missing.xout) x else xout 15 | 16 | if (missing.xout || identical(xout, index(object))) { 17 | result <- object 18 | } else { 19 | object.x <- object 20 | if (!identical(class(x), class(xout))) { 21 | index(object.x) <- as.numeric(x) 22 | xout <- as.numeric(xout) 23 | } else { 24 | index(object.x) <- x 25 | } 26 | objectm <- merge(object.x, zoo(, xout)) 27 | if (length(dim(objectm)) == 2) colnames(objectm) <- colnames(object) 28 | result <- window(objectm, index = xout) 29 | } 30 | result[] <- na.spline.default(object, x = x, xout = xout, na.rm = FALSE, ..., maxgap = maxgap) 31 | if ((!missing(order.by) && !is.null(order.by)) || !missing.xout) { 32 | index(result) <- order.by 33 | } 34 | 35 | if (na.rm) { 36 | result <- na.trim(result, is.na = "all", maxgap = maxgap) 37 | } 38 | 39 | result 40 | 41 | } 42 | 43 | na.spline.zooreg <- function(object, ...) { 44 | object. <- structure(object, class = setdiff(class(object), "zooreg")) 45 | as.zooreg(na.spline(object., ...)) 46 | } 47 | 48 | 49 | na.spline.default <- function(object, x = index(object), xout = x, ..., na.rm = TRUE, maxgap = Inf, along) { 50 | 51 | if (!missing(along)) { 52 | warning("along to be deprecated - use x instead") 53 | if (missing(x)) x <- along 54 | } 55 | 56 | na.spline.vec <- function(x, y, xout = x, ...) { 57 | na <- is.na(y) 58 | if(sum(!na) < 1L) { 59 | ## splinefun() cannot be applied here, hence simply: 60 | yf <- rep.int(NA, length(xout)) 61 | mode(yf) <- mode(y) 62 | if(any(!na)) { 63 | if(x[!na] %in% xout) { 64 | yf[xout == x[!na]] <- y[!na] 65 | } 66 | } 67 | return(yf) 68 | } 69 | if(all(!na) && (length(xout) > maxgap) && !all(xout %in% x)) { 70 | ## for maxgap to work correctly 'y' has to contain 71 | ## actual NAs and be expanded to the full x-index 72 | xf <- sort(unique(c(x, xout))) 73 | yf <- rep.int(NA, length(xf)) 74 | yf[MATCH(x, xf)] <- y 75 | x <- xf 76 | y <- yf 77 | } 78 | yf <- splinefun(x[!na], y[!na], ...)(xout) 79 | if (maxgap < length(y)) { 80 | ## construct a series like y but with only gaps > maxgap 81 | ## (actual values don't matter as we only use is.na(ygap) below) 82 | ygap <- .fill_short_gaps(y, seq_along(y), maxgap = maxgap) 83 | ## construct y values at 'xout', keeping NAs from ygap 84 | ## (using indexing, as approx() does not allow NAs to be propagated) 85 | ix <- splinefun(x, seq_along(y), ...)(xout) 86 | yx <- ifelse(is.na(ygap[floor(ix)] + ygap[ceiling(ix)]), NA, yf) 87 | yx 88 | } else { 89 | yf 90 | } 91 | } 92 | 93 | if (!identical(length(x), length(index(object)))) { 94 | stop("x and index must have the same length") 95 | } 96 | x. <- as.numeric(x) 97 | if (missing(xout) || is.null(xout)) xout <- x. 98 | xout. <- as.numeric(xout) 99 | object. <- coredata(object) 100 | 101 | result <- if (length(dim(object.)) < 2) { 102 | na.spline.vec(x., coredata(object.), xout = xout., ...) 103 | } else { 104 | apply(coredata(object.), 2, na.spline.vec, x = x., xout = xout., ...) 105 | } 106 | 107 | if (na.rm) { 108 | result <- na.trim(result, is.na = "all", maxgap = maxgap) 109 | } 110 | 111 | result 112 | 113 | } 114 | 115 | na.spline.ts <- function(object, ...) { 116 | as.ts(na.spline(as.zoo(object), ...)) 117 | } 118 | 119 | -------------------------------------------------------------------------------- /R/na.trim.R: -------------------------------------------------------------------------------- 1 | na.trim <- function(object, ...) UseMethod("na.trim") 2 | na.trim.default <- function (object, sides = c("both", "left", "right"), 3 | is.na = c("any", "all"), maxgap = Inf, ...) 4 | { 5 | is.na <- match.arg(is.na, c("any", "all")) 6 | nisna <- if (is.na == "any" || length(dim(object)) < 2L) { 7 | complete.cases(object) 8 | } else rowSums(!is.na(object)) > 0 9 | rlength <- function(x) if(all(!x)) length(x) else min(which(x)) - 1L 10 | idx <- switch(match.arg(sides), 11 | left = { 12 | idx0 <- cumsum(nisna) > 0 13 | idx0 | rlength(idx0) > maxgap 14 | }, 15 | right = { 16 | idx0 <- cumsum(rev(nisna) > 0) > 0 17 | rev(idx0) | rlength(idx0) > maxgap 18 | }, 19 | both = { 20 | idx0l <- cumsum(nisna) > 0 21 | idx0r <- cumsum(rev(nisna) > 0) > 0 22 | (idx0l | rlength(idx0l) > maxgap) & (rev(idx0r) | rlength(idx0r) > maxgap) 23 | } 24 | ) 25 | if (length(dim(object)) < 2L) 26 | object[idx] 27 | else 28 | object[idx,, drop = FALSE] 29 | } 30 | 31 | ## need a 'ts' method because indexing destroys ts attributes 32 | na.trim.ts <- function (object, ...) 33 | { 34 | as.ts(na.trim(as.zoo(object), ...)) 35 | } 36 | -------------------------------------------------------------------------------- /R/rollapply.R: -------------------------------------------------------------------------------- 1 | 2 | # data is a zoo object or a plain vector or matrix 3 | # 4 | # width is 5 | # - a list of integer vectors representing offsets or a plain vector of widths. 6 | # There is one per time point or its recycled if too short. recycling uses 7 | # by= argument if length(width) is 1; otherwise, by is ignored. 8 | # If width represents widths then they are turned into offsets using align. 9 | # 10 | # If we are at 5th time of data and width[[5]] is c(-2,-1,0) then FUN is applied 11 | # to positions i + width[[i]] = 5 + c(-2,-1,0) = 3:5 of z (so in terms of 12 | # a width specification it would be the same as width = 3, align = "right"). 13 | # 14 | # Therefore we have the following transformations: 15 | # widths are converted to offsets which are converted to positions. 16 | # The offsets are the components of width and the 17 | # positions are i+width[[i]] after partial processing. partial can be: 18 | # - logical. FALSE means that all offets must exist or else no result is 19 | # produced for that time point. TRUE means that at least one offset must 20 | # exist. 21 | # - numeric. The minimum number of offsets that must exist. If < 0 then 22 | # all elements of the offset must exist. Note that TRUE corresponds to 1 23 | # and FALSE correspoinds to -1. These are the two most common values. 24 | # 25 | # For points that are not computed they are filled in with fill. fill has 26 | # three elements and is recycled if too short. fill = NULL is the default. 27 | # The elements represent what to fill the left points, interior points and 28 | # right points. NULL causes no filling and "extend" causes the first or 29 | # last point to be repeated or interior points to be linearly approximated. 30 | 31 | # wrapper around rollapply which defaults to align = "right" 32 | rollapplyr <- function(..., align = "right") { 33 | rollapply(..., align = align) 34 | } 35 | 36 | rollapply <- function(data, ...) UseMethod("rollapply") 37 | 38 | rollapply.default <- function(data, ...) { 39 | if (length(data) < 1L) return(data) 40 | coredata(rollapply(zoo(data), ...)) 41 | } 42 | 43 | rollapply.ts <- function(data, ...) { 44 | if (length(data) < 1L) return(data) 45 | as.ts(rollapply(as.zoo(data), ...)) 46 | } 47 | 48 | rollapply.zoo <- function(data, width, FUN, ..., by = 1, 49 | by.column = TRUE, fill = if (na.pad) NA, na.pad = FALSE, 50 | partial = FALSE, align = c("center", "left", "right"), coredata = TRUE) { 51 | 52 | if (length(data) < 1L) return(data) 53 | 54 | if (!missing(na.pad)) { 55 | warning("na.pad argument is deprecated") 56 | } 57 | 58 | if (is.vector(width) && !is.list(width) && length(width) == 1 && 59 | by.column && length(by) == 1 && by == 1 && (missing(partial) | identical(partial, FALSE)) && 60 | length(list(...)) < 1 && length(sw <- deparse(substitute(FUN))) == 1) { 61 | if (sw == "mean" && !anyNA(data)) { 62 | return(rollmean(data, width, fill = fill, align = align)) 63 | } else if (sw == "median" && width %% 2 == 1 && !anyNA(data)) { 64 | return(rollmedian(data, width, fill = fill, align = align)) 65 | } else if (sw == "max") { 66 | return(rollmax(data, width, fill = fill, align = align)) 67 | } 68 | } 69 | FUN <- match.fun(FUN) 70 | 71 | if (by.column && length(dim(data)) == 2) { 72 | z <- do.call(merge, 73 | lapply(1:NCOL(data), function(j) 74 | rollapply(data[, j, drop = TRUE], width = width, FUN = FUN, ..., 75 | by = by, by.column = by.column, fill = fill, 76 | partial = partial, align = align, coredata = coredata) 77 | ) 78 | ) 79 | if (NCOL(data) == 1) dim(z) <- c(length(z), 1) 80 | colnames(z) <- if (NCOL(z) == NCOL(data)) colnames(data) 81 | return(z) 82 | } 83 | 84 | if (is.logical(partial)) partial <- if (partial) 1 else -1 85 | 86 | # convert widths to offsets using align 87 | align <- match.arg(align) 88 | 89 | width <- if (!is.list(width)) { 90 | lapply(trunc(width), function(w) { 91 | if (align == "right") seq(to = 0, length.out = w) 92 | else if (align == "center") seq(to = floor(w/2), length.out = w) 93 | else seq(from = 0, length.out = w) 94 | }) 95 | } else { 96 | lapply(width, function(w) { 97 | if(is.null(w)) NULL else trunc(w) 98 | }) 99 | } 100 | # recycle width (using by if length(width) == 1) 101 | width <- if (length(width) == 1) { 102 | w <- rep(list(NULL), NROW(data)) 103 | start.at <- if (partial < 0) max(-min(width[[1]]), 0) + 1 else 1 104 | start.at <- min(NROW(data), start.at) 105 | replace(w, seq(start.at, NROW(data), by = by), width) 106 | } else rep(width, length.out = NROW(data)) 107 | 108 | f <- if (is.null(dim(data))) { 109 | # undimensioned 110 | # 111 | # if FUN is to be evaluated at offsets for the ith point then calculate 112 | # positions, do partial processing and apply FUN 113 | function(i, offsets, data, ...) { 114 | if (is.null(offsets)) return(NULL) 115 | posns <- i + offsets 116 | ix <- posns >= 1 & posns <= NROW(data) 117 | if (partial < 0) { 118 | if (all(ix)) FUN(data[posns], ...) 119 | } else if (sum(ix) >= partial) { 120 | FUN(data[replace(posns, !ix, 0)], ...) 121 | } 122 | } 123 | } else { 124 | # dimensioned 125 | # 126 | # same f as in TRUE leg except data[.] becomes data[.,] 127 | function(i, offsets, data, ...) { 128 | if (is.null(offsets)) return(NULL) 129 | posns <- i + offsets 130 | ix <- posns >= 1 & posns <= NROW(data) 131 | if (partial < 0) { 132 | if (all(ix)) FUN(data[posns,], ...) 133 | } else if (sum(ix) >= partial) { 134 | FUN(data[replace(posns, !ix, 0),], ...) 135 | } 136 | } 137 | } 138 | 139 | dat <- if(coredata) coredata(data) else data 140 | dat <- mapply(f, seq_along(time(data)), width, 141 | MoreArgs = list(data = dat, ...), SIMPLIFY = FALSE) 142 | 143 | ix <- !sapply(dat, is.null) # integer indexes of non-nulls 144 | 145 | ## flatten data if output of FUN has a dim and > 1 row (e.g., matrix or data.frame) 146 | if(any(sapply(dat[ix], function(d) !is.null(nrow(d)) && nrow(d) > 1L))) { 147 | dat[ix] <- lapply(dat[ix], function(d) unlist(as.data.frame(d))) 148 | } 149 | 150 | if (!missing(fill) || !missing(na.pad)) { 151 | 152 | # replace NULLs with NAs 153 | dat <- lapply(dat, function(x) if (is.null(x)) NA else x) 154 | 155 | # construct zoo object 156 | dat <- 157 | if (max(sapply(dat, length)) > 1) 158 | zoo(do.call("rbind", dat), index(data), attr(data, "frequency")) 159 | else 160 | zoo(do.call("c", dat), index(data), attr(data, "frequency")) 161 | 162 | # perform filling 163 | dat <- na.fill(dat, fill, ix) 164 | 165 | } else { 166 | 167 | # construct zoo object removing points corresponding to NULL 168 | dat <- if (max(sapply(dat, length)) > 1) 169 | zoo(do.call("rbind", dat), index(data)[ix], attr(data, "frequency")) 170 | else 171 | zoo(do.call("c", dat), index(data)[ix], attr(data, "frequency")) 172 | } 173 | 174 | dat 175 | } 176 | -------------------------------------------------------------------------------- /R/tinyplot.zoo.R: -------------------------------------------------------------------------------- 1 | tinyplot.zoo <- function(object, facet, type = "l", facet.args = list(free = TRUE), ylab = "", ...) 2 | { 3 | ## convert to data.frame (and assure correct label processing by fortify.zoo) 4 | lab <- deparse(substitute(object)) 5 | if(NCOL(object) == 1L) { 6 | if(is.null(dim(object))) dim(object) <- c(NROW(object), 1L) 7 | if(is.null(colnames(object))) colnames(object) <- lab 8 | } 9 | if(is.null(colnames(object))) colnames(object) <- paste(lab, 1:NCOL(object), sep = ".") 10 | df <- fortify.zoo(object, melt = TRUE) 11 | 12 | ## default for facet 13 | single <- nlevels(df$Series) == 1L 14 | if(missing(facet)) { 15 | auto <- TRUE 16 | facet <- if(single) NULL else ~ Series 17 | } else { 18 | auto <- FALSE 19 | } 20 | if (is.null(facet)) facet.args <- NULL 21 | 22 | ## call tinyplot 23 | if(single | (!is.null(facet) & auto)) { 24 | tinyplot::tinyplot(Value ~ Index, data = df, facet = facet, facet.args = facet.args, type = type, ylab = ylab, ...) 25 | } else { 26 | tinyplot::tinyplot(Value ~ Index | Series, data = df, facet = facet, facet.args = facet.args, type = type, ylab = ylab, ...) 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /R/window.zoo.R: -------------------------------------------------------------------------------- 1 | window.zoo <- function(x, index. = index(x), start = NULL, end = NULL, ...) 2 | { 3 | all.indexes <- index(x) 4 | in.index <- MATCH(all.indexes, index., nomatch = 0) > 0 5 | 6 | if(length(start) == 2 && !is.null(attr(x, "frequency")) && is.numeric(all.indexes)) { 7 | freq <- attr(x, "frequency") 8 | start <- floor(start[1]*freq + (start[2] - 1) + .0001)/freq 9 | } 10 | if(length(end) == 2 && !is.null(attr(x, "frequency")) && is.numeric(all.indexes)) { 11 | freq <- attr(x, "frequency") 12 | end <- floor(end[1]*freq + (end[2] - 1) + .0001)/freq 13 | } 14 | 15 | if(is.null(start) || any(is.na(start))) { 16 | if(is.null(end) || any(is.na(end))) { 17 | wi <- which(MATCH(all.indexes, index., nomatch = 0) > 0) 18 | return(x[wi, , drop = FALSE]) 19 | } else { 20 | wi <- which(in.index & all.indexes <= end) 21 | return(x[wi, , drop = FALSE]) 22 | } 23 | } else { 24 | if(is.null(end) || any(is.na(end))) { 25 | wi <- which(in.index & all.indexes >= start) 26 | } else { 27 | wi <- which(in.index & all.indexes >= start & all.indexes <= end) 28 | } 29 | return(x[wi, , drop = FALSE]) 30 | } 31 | } 32 | 33 | "window<-.zoo" <- function(x, index. = index(x), start = NULL, end = NULL, ..., value) 34 | { 35 | ix <- index(x) 36 | stopifnot(all(MATCH(index., ix, nomatch = 0) > 0)) 37 | 38 | if(length(start) == 2 && !is.null(attr(x, "frequency")) && is.numeric(ix)) { 39 | freq <- attr(x, "frequency") 40 | start <- floor(start[1]*freq + (start[2] - 1) + .0001)/freq 41 | } 42 | if(length(end) == 2 && !is.null(attr(x, "frequency")) && is.numeric(ix)) { 43 | freq <- attr(x, "frequency") 44 | end <- floor(end[1]*freq + (end[2] - 1) + .0001)/freq 45 | } 46 | 47 | if (!is.null(start) && !is.na(start)) index. <- index.[index. >= start] 48 | if (!is.null(end) && !is.na(end)) index. <- index.[index. <= end] 49 | 50 | wi <- which(MATCH(ix, index., nomatch = 0) > 0) 51 | if (length(dim(x)) == 0) 52 | x[wi] <- value 53 | else 54 | x[wi,] <- value 55 | return(x) 56 | } 57 | 58 | lag.zoo <- function(x, k = 1, na.pad = FALSE, ...) 59 | { 60 | if (length(k) > 1) { 61 | if (is.null(names(k))) names(k) <- paste("lag", k, sep = "") 62 | return(do.call("merge.zoo", lapply(k, lag.zoo, x = x, na.pad = na.pad, ...))) 63 | } 64 | nr <- NROW(x) 65 | if (k != round(k)) { 66 | k <- round(k) 67 | warning("k is not an integer") 68 | } 69 | if (k == 0) return(x) 70 | if (abs(k) > nr) k <- nr 71 | if (k > 0) { 72 | xx <- x[-seq(1, length.out = k),, drop = FALSE] 73 | attr(xx, "index") <- index(x)[-seq(to = nr, length.out = k)] 74 | } else { 75 | xx <- x[-seq(to = nr, length.out = -k),, drop = FALSE] 76 | attr(xx, "index") <- index(x)[-seq(1, length.out = -k)] 77 | } 78 | if (na.pad) merge(zoo(,time(x)), xx, all = c(TRUE, FALSE)) else xx 79 | } 80 | 81 | 82 | 83 | lag.zooreg <- function(x, k = 1, na.pad = FALSE, ...) 84 | { 85 | if (length(k) > 1) { 86 | if (is.null(names(k))) names(k) <- paste("lag", k, sep = "") 87 | return(do.call("merge.zoo", lapply(k, lag.zooreg, x = x, na.pad = na.pad, ...))) 88 | } 89 | x0 <- x 90 | nr <- NROW(x) 91 | freq <- attr(x, "frequency") 92 | 93 | if (k != round(k)) warning("k is not an integer") 94 | k <- round(k) 95 | 96 | ix <- index(x) 97 | ix <- if(identical(class(ix), "numeric") | identical(class(ix), "integer")) 98 | floor(freq*ix - k + .0001)/freq else ix - k/freq 99 | index(x) <- ix 100 | 101 | if (na.pad) merge(x, zoo(, time(x0))) else x 102 | } 103 | 104 | diff.zoo <- function(x, lag = 1, differences = 1, arithmetic = TRUE, na.pad = FALSE, log = FALSE, ...) 105 | { 106 | ix <- index(x) 107 | stopifnot(differences >= 1) 108 | 109 | ## for relative differences, use division only if 'x' contains negative values 110 | ## other numerically more stable log-transform 111 | if(arithmetic || all(coredata(x) > 0)) { 112 | if (!arithmetic || log) x <- log(x) 113 | if (lag > 0) for(i in 1:differences) x <- x - lag(x, k = -lag, ...) else for(i in 1:differences) x <- lag(x, k = -lag, ...) - x 114 | if (!arithmetic) x <- exp(x) 115 | } else { 116 | if (lag > 0) for(i in 1:differences) x <- x / lag(x, k = -lag, ...) else for(i in 1:differences) x <- lag(x, k = -lag, ...) / x 117 | } 118 | if (na.pad) merge(zoo(,ix), x, all = c(TRUE, FALSE)) else x 119 | } 120 | -------------------------------------------------------------------------------- /R/xblocks.R: -------------------------------------------------------------------------------- 1 | 2 | xblocks <- function(x, ...) 3 | UseMethod("xblocks") 4 | 5 | xblocks.default <- 6 | function (x, y, ..., col = NULL, border = NA, 7 | ybottom = par("usr")[3], ytop = ybottom + height, 8 | height = diff(par("usr")[3:4]), 9 | last.step = median(diff(tail(x)))) 10 | { 11 | if (is.function(y)) 12 | y <- y(x) 13 | x <- as.numeric(x) 14 | if (length(x) == 0) return() 15 | if (is.unsorted(x, na.rm = TRUE)) 16 | stop("'x' should be ordered (increasing)") 17 | if (is.na(last.step)) 18 | last.step <- 0 19 | ## Three cases: 20 | ## (1) If y is character, assume it gives the block colours 21 | ## -- unless 'col' is given, which over-rides it. 22 | ## (2) If y is logical, show blocks of TRUE values. 23 | ## (3) If y is numeric, show blocks of non-NA values. 24 | if (is.logical(y)) { 25 | y <- y 26 | } else if (is.numeric(y)) { 27 | y <- !is.na(y) 28 | } else { 29 | ## this will convert factor, Date, etc to character: 30 | y <- as.character(y) 31 | } 32 | ## Note: rle treats each NA as unique (does not combine runs of NAs) 33 | ## so we need to replace NAs with a temporary value. 34 | NAval <- 35 | if (is.character(y)) "" else FALSE 36 | y[is.na(y)] <- NAval 37 | ## find blocks (runs of constant values) 38 | yrle <- rle(y) 39 | ## substitute NA values back in 40 | blockCol <- yrle$values 41 | blockCol[blockCol == NAval] <- NA 42 | ## for logical series, col default comes from palette() 43 | if (is.logical(y) && is.null(col)) 44 | col <- palette()[1] 45 | ## set block colours if 'col' given 46 | if (length(col) > 0) { 47 | if (is.character(col)) 48 | col[col == ""] <- NA 49 | ok <- !is.na(blockCol) 50 | blockCol[ok] <- rep(col, length.out = sum(ok)) ## rep to avoid warnings 51 | } 52 | ## work out block geometry 53 | idxBounds <- cumsum(c(1, yrle$lengths)) 54 | idxStart <- head(idxBounds, -1) 55 | idxEnd <- tail(idxBounds, -1) 56 | idxEnd[length(idxEnd)] <- length(y) 57 | blockStart <- x[idxStart] 58 | blockEnd <- x[idxEnd] 59 | blockEnd[length(blockEnd)] <- tail(blockEnd, 1) + last.step 60 | blockWidth <- blockEnd - blockStart 61 | ## adjust for log scales 62 | if (par("ylog")) { 63 | ybottom <- 10^ybottom 64 | ytop <- 10^ytop 65 | } 66 | ## draw it 67 | rect(xleft = blockStart, xright = blockEnd, 68 | ybottom = ybottom, ytop = ytop, 69 | col = blockCol, border = border, ...) 70 | } 71 | 72 | xblocks.zoo <- 73 | xblocks.ts <- 74 | function(x, y = x, ...) 75 | { 76 | if (!is.function(y)) 77 | y <- coredata(y) 78 | xblocks(index(x), y, ...) 79 | } 80 | -------------------------------------------------------------------------------- /R/xyplot.zoo.R: -------------------------------------------------------------------------------- 1 | panel.plot.default <- function(x, y, subscripts, groups, panel = panel.xyplot, 2 | col = 1, type = "p", pch = 20, lty = 1, lwd = 1, ...) 3 | { 4 | col <- rep(as.list(col), length.out = nlevels(groups)) 5 | type <- rep(as.list(type), length.out = nlevels(groups)) 6 | pch <- rep(as.list(pch), length.out = nlevels(groups)) 7 | lty <- rep(as.list(lty), length.out = nlevels(groups)) 8 | lwd <- rep(as.list(lwd), length.out = nlevels(groups)) 9 | 10 | for(g in 1:nlevels(groups)) { 11 | idx <- g == unclass(groups[subscripts]) 12 | if (any(idx)) panel(x[idx], y[idx], ..., 13 | col = col[[g]], type = type[[g]], pch = pch[[g]], 14 | lty = lty[[g]], lwd = lwd[[g]]) 15 | } 16 | .Deprecated(msg="panel.plot.default is no longer needed, just use panel.xyplot etc") 17 | } 18 | 19 | panel.plot.custom <- function(...) { 20 | args <- list(...) 21 | function(...) { 22 | dots <- list(...) 23 | do.call("panel.plot.default", modifyList(dots, args)) 24 | } 25 | } 26 | 27 | xyplot.its <- 28 | xyplot.ts <- 29 | xyplot.zoo <- function(x, data, ...) 30 | { 31 | obj <- lattice::xyplot.ts(as.zoo(x), ...) 32 | obj$call <- match.call() 33 | obj 34 | } 35 | 36 | xyplot.tis <- function(x, data, ...) 37 | { 38 | x <- aggregate(as.zoo(x), tis::POSIXct, identity) 39 | obj <- lattice::xyplot.ts(x, ...) 40 | obj$call <- match.call() 41 | obj 42 | } 43 | 44 | 45 | llines.its <- 46 | llines.tis <- 47 | llines.zoo <- function(x, y = NULL, ...) 48 | { 49 | if (!is.null(y)) { 50 | llines(coredata(x), y = y, ...) 51 | } else { 52 | llines(coredata(time(x)), y = coredata(x), ...) 53 | } 54 | } 55 | 56 | lpoints.its <- 57 | lpoints.tis <- 58 | lpoints.zoo <- function(x, y = NULL, ...) 59 | { 60 | if (!is.null(y)) { 61 | lpoints(coredata(x), y = y, ...) 62 | } else { 63 | lpoints(coredata(time(x)), y = coredata(x), ...) 64 | } 65 | } 66 | 67 | ltext.its <- 68 | ltext.tis <- 69 | ltext.zoo <- function(x, y = NULL, ...) 70 | { 71 | if (!is.null(y)) { 72 | ltext(coredata(x), y = y, ...) 73 | } else { 74 | ltext(coredata(time(x)), y = coredata(x), ...) 75 | } 76 | } 77 | 78 | 79 | panel.lines.ts <- 80 | panel.lines.its <- 81 | panel.lines.tis <- 82 | panel.lines.zoo <- function(x, ...) { 83 | x <- as.zoo(x) 84 | panel.lines(time(x), coredata(x), ...) 85 | .Deprecated("panel.lines") 86 | } 87 | 88 | panel.points.ts <- 89 | panel.points.its <- 90 | panel.points.tis <- 91 | panel.points.zoo <- function(x, ...) { 92 | x <- as.zoo(x) 93 | panel.points(time(x), coredata(x), ...) 94 | .Deprecated("panel.points") 95 | } 96 | 97 | panel.text.ts <- 98 | panel.text.its <- 99 | panel.text.tis <- 100 | panel.text.zoo <- function(x, ...) { 101 | x <- as.zoo(x) 102 | panel.text(time(x), coredata(x), ...) 103 | .Deprecated("panel.text") 104 | } 105 | 106 | panel.segments.ts <- 107 | panel.segments.its <- 108 | panel.segments.tis <- 109 | panel.segments.zoo <- function(x0, x1, ...) { 110 | x0 <- as.zoo(x0) 111 | x1 <- as.zoo(x1) 112 | panel.segments(time(x0), coredata(x0), time(x1), coredata(x1), ...) 113 | } 114 | 115 | panel.rect.ts <- 116 | panel.rect.its <- 117 | panel.rect.tis <- 118 | panel.rect.zoo <- function(x0, x1, ...) { 119 | x0 <- as.zoo(x0) 120 | x1 <- as.zoo(x1) 121 | panel.rect(time(x0), coredata(x0), time(x1), coredata(x1), ...) 122 | } 123 | 124 | panel.polygon.ts <- 125 | panel.polygon.its <- 126 | panel.polygon.tis <- 127 | panel.polygon.zoo <- function(x, ...) { 128 | x <- as.zoo(x) 129 | panel.polygon(time(x), coredata(x), ...) 130 | } 131 | -------------------------------------------------------------------------------- /R/zooreg.R: -------------------------------------------------------------------------------- 1 | zooreg <- function(data, start = 1, end = numeric(), frequency = 1, 2 | deltat = 1, ts.eps = getOption("ts.eps"), order.by = NULL, 3 | calendar = getOption("zoo.calendar", TRUE)) 4 | { 5 | ## choose frequency/deltat 6 | if (missing(frequency)) frequency <- 1/deltat 7 | else if(missing(deltat)) deltat <- 1/frequency 8 | if (frequency > 1 && abs(frequency - round(frequency)) < ts.eps) 9 | frequency <- round(frequency) 10 | 11 | ## detect if integer index is intended 12 | intgr <- ((length(start) < 1L) || is.integer(start)) && ((length(end) < 1L) || is.integer(end)) 13 | 14 | ## check data and choose default 15 | if (missing(data) || is.null(data)) data <- NA 16 | if(!(is.vector(data) || is.factor(data) || is.atomic(data) || is.matrix(data) || is.data.frame(data))) 17 | stop(paste(dQuote("data"), ": attempt to define invalid zoo object")) 18 | if(is.matrix(data) || is.data.frame(data)) data <- as.matrix(data) 19 | 20 | ## if no index (i.e., order.by) is specified: behave as ts() 21 | ## else: behave as zoo() 22 | if (is.null(order.by)) { 23 | if(!any(c(is.vector(data), is.factor(data), is.atomic(data), is.matrix(data), is.data.frame(data)))) 24 | stop(paste(dQuote("data"), ": attempt to define invalid zoo object")) 25 | ndata <- NROW(data) 26 | 27 | ## convenience function 28 | numORint <- function(x) identical(class(x), "numeric") || identical(class(x), "integer") 29 | 30 | ## choose start/end 31 | if (length(start) > 1) start <- start[1] + (start[2] - 1)/frequency 32 | if (length(end) > 1) end <- end[1] + (end[2] - 1)/frequency 33 | if (missing(end)) { 34 | ostart <- start 35 | oend <- NULL 36 | start <- as.numeric(start) 37 | end <- start + (ndata - 1)/frequency 38 | } else if(missing(start)) { 39 | ostart <- NULL 40 | oend <- end 41 | end <- as.numeric(end) 42 | start <- end - (ndata - 1)/frequency 43 | } else{ 44 | ostart <- start 45 | oend <- NULL 46 | start <- as.numeric(start) 47 | end <- as.numeric(end) 48 | } 49 | if (start > end) stop("start cannot be after end") 50 | 51 | ## check whether lengths of data and index match 52 | # wrong lengths sometimes: order.by <- seq(start, end, by = deltat) 53 | order.by <- start + seq(0, length.out = ndata) * deltat 54 | if(isTRUE(all.equal(start * frequency, round(start * frequency), tolerance = ts.eps^2))) { 55 | order.by <- floor(frequency * order.by + .0001)/frequency 56 | } 57 | 58 | ## support also non-numeric indexes 59 | if(!is.null(ostart) && !numORint(ostart)) 60 | order.by <- ostart + (order.by - start) 61 | if(!is.null(oend) && !numORint(oend)) 62 | order.by <- oend + (order.by - end) 63 | 64 | nobs <- length(order.by) 65 | ## nobs <- floor((end - start) * frequency + 1.01) 66 | if (nobs != ndata) { 67 | if(is.vector(data)) data <- rep(data, length.out = nobs) 68 | else if(is.factor(data)) data <- factor(rep(as.character(data), length.out = nobs), labels = levels(data)) 69 | else if(is.matrix(data) || is.data.frame(data)) data <- data[rep(1:ndata, length.out = nobs), , drop = FALSE] 70 | } 71 | 72 | ## support of calendar index (yearqtr/yearmon) for quarterly/monthly data 73 | if(calendar && frequency %in% c(4, 12) && numORint(order.by)) { 74 | order.by <- if(frequency == 4) as.yearqtr(order.by) else as.yearmon(order.by) 75 | } else if(intgr) { 76 | if(isTRUE(all.equal(order.by, round(order.by), tolerance = ts.eps^2))) order.by <- as.integer(round(order.by)) 77 | } 78 | 79 | attr(data, "oclass") <- attr(data, "class") 80 | attr(data, "index") <- order.by 81 | attr(data, "frequency") <- frequency 82 | class(data) <- c("zooreg", "zoo") 83 | return(data) 84 | } else { 85 | return(zoo(data, order.by, frequency)) 86 | } 87 | } 88 | 89 | rev.zooreg <- function(x) { z <- as.zooreg(rev(as.zoo(x))); frequency(z) <- frequency(x); z } 90 | -------------------------------------------------------------------------------- /R/zzz.R: -------------------------------------------------------------------------------- 1 | register_s3_method <- function(pkg, generic, class, fun = NULL) { 2 | stopifnot(is.character(pkg), length(pkg) == 1L) 3 | stopifnot(is.character(generic), length(generic) == 1L) 4 | stopifnot(is.character(class), length(class) == 1L) 5 | 6 | if (is.null(fun)) { 7 | fun <- get(paste0(generic, ".", class), envir = parent.frame()) 8 | } else { 9 | stopifnot(is.function(fun)) 10 | } 11 | 12 | if (isNamespaceLoaded(pkg)) { 13 | registerS3method(generic, class, fun, envir = asNamespace(pkg)) 14 | } 15 | 16 | # Always register hook in case package is later unloaded & reloaded 17 | setHook( 18 | packageEvent(pkg, "onLoad"), 19 | function(...) { 20 | registerS3method(generic, class, fun, envir = asNamespace(pkg)) 21 | } 22 | ) 23 | } 24 | 25 | .onLoad <- function(libname, pkgname) { 26 | if(getRversion() < "3.6.0") { 27 | register_s3_method("ggplot2", "autoplot", "zoo") 28 | register_s3_method("ggplot2", "fortify", "zoo") 29 | register_s3_method("ggplot2", "scale_type", "yearmon") 30 | register_s3_method("ggplot2", "scale_type", "yearqtr") 31 | } 32 | invisible() 33 | } 34 | 35 | .onUnload <- function(libpath) { 36 | library.dynam.unload("zoo", libpath) 37 | } 38 | -------------------------------------------------------------------------------- /build/vignette.rds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cran/zoo/d032ed0519de3eeefe651ad9f25f7408461732a0/build/vignette.rds -------------------------------------------------------------------------------- /demo/00Index: -------------------------------------------------------------------------------- 1 | zoo-overplot Plot time series in black with certain regions in red. 2 | -------------------------------------------------------------------------------- /inst/CITATION: -------------------------------------------------------------------------------- 1 | bibentry(bibtype = "Article", 2 | title = "zoo: S3 Infrastructure for Regular and Irregular Time Series", 3 | author = c(person(given = "Achim", family = "Zeileis"), 4 | person(given = "Gabor", family = "Grothendieck")), 5 | journal = "Journal of Statistical Software", 6 | year = "2005", 7 | volume = "14", 8 | number = "6", 9 | pages = "1--27", 10 | doi = "10.18637/jss.v014.i06", 11 | header = "To cite zoo in publications use:" 12 | ) 13 | -------------------------------------------------------------------------------- /inst/THANKS: -------------------------------------------------------------------------------- 1 | The authors would like to thank the following people for ideas, 2 | testing and feedback regarding zoo: 3 | Whit Armstrong 4 | Matthieu Cormec 5 | Spencer Graves 6 | Sundar Dorai-Raj 7 | Dirk Eddelbuettel 8 | Mario Frasca 9 | Christian Gunning 10 | Nicolas Hirschey 11 | Kurt Hornik 12 | Roger Koenker 13 | Thomas McCallum 14 | Murali.MENON@fortisinvestments.com 15 | Deepayan Sarkar 16 | Enrico Schumann 17 | Ajay Shah 18 | Jarek Tuszynski 19 | Felix Andrews 20 | Giles Heywood 21 | Trevor Davis 22 | -------------------------------------------------------------------------------- /inst/TODO: -------------------------------------------------------------------------------- 1 | 2 | - add to unit tests. There are two styles: (1) in zoo/tests using the R CMD check facilities and (2) in zoo/inst/unitTests using the RUnit package. 3 | 4 | - benchmark zoo with and without byte compiling to see what the difference is. If this is fast enough the next point may not be needed. Targets of the test would be merge.zoo, rollapply.zoo, etc. e.g in the following the compiler was actually slower: 5 | 6 | > library(rbenchmark) 7 | > library(compiler) 8 | > f <- function(x) x*x 9 | > fc <- cmpfun(f) 10 | > benchmark(f(100), fc(100)) 11 | test replications elapsed relative user.self sys.self user.child sys.child 12 | 1 f(100) 100 0.00 0 0.00 0 NA NA 13 | 2 fc(100) 100 0.02 1 0.01 0 NA NA 14 | 15 | - xts is like zoo but only works with the half dozen most popular index classes. Some of its functionality is made possible by that but other functionality could be ported to zoo. 16 | 17 | - consolidate the C code in xts and zoo so that they both use the same C code base. xts already uses a C backend so its more a matter of getting it to use zoo. This really needs more unit tests to be done first. Also the byte compiler needs to be tested to see if it can give similar speedups. If it can there is no point in this one. 18 | 19 | - a user contributed code to do rolling analysis by time difference rather than number of points. This needs to be gone over. 20 | 21 | - rewrite merge.zoo which has become a mess 22 | 23 | 24 | -------------------------------------------------------------------------------- /inst/WISHLIST: -------------------------------------------------------------------------------- 1 | FEATURES 2 | ******** 3 | 4 | o within.zoo 5 | 6 | o rollapply.default that does not work via zoo+"unzoo". 7 | 8 | o rbind.zoo() currently ignores the column names (if any), 9 | should behave like rbind.data.frame() in this case. 10 | 11 | o design: re-think shared design of parameter and panel 12 | functions for plotting. 13 | 14 | o bugs: rollmax, rollmedian give Error for k=1. 15 | 16 | o zoo methods for dbReadTable and dbWriteTable to facilitate 17 | using zoo objects with DBI 18 | 19 | o register S3 methods and use namespaces so that this works: 20 | f <- local(function(x) zoo::index(x), baseenv()) 21 | 22 | o provide a [<-.zoo method that is fully consistent with [.zoo 23 | so that the following works: 24 | a <- zoo(matrix(1:10,5,2), 2001:2005) 25 | a[I(2003), 2] <- NA 26 | (Note: as in window<-.zoo) 27 | 28 | o preserve attributes in [.zoo and possibly certain other 29 | zoo methods 30 | 31 | o allow plot.zoo to accept a list of zoo objects -- this would 32 | be particularly useful in the case of line plots of multiple series 33 | with different time bases since NAs are introduced by merging 34 | and they can cause the drawn lines to be undesirably broken. 35 | (Current workaround is to use na.approx.) 36 | 37 | o more graphical facilities, e.g., a pairs function, make 38 | plot.zoo(x, y) work with multivariate series (plotting every 39 | combination of plot(x[,i], y[,j])) 40 | 41 | o incorporate runmean in package caMassClass 42 | 43 | o allow log to be specified per plot in plot.zoo 44 | 45 | o performance enhancement when using arithmetic on zoo objects. Check 46 | if they have same index first. 47 | 48 | o speedup for indexing strictly regular series. Test with is.regular first. 49 | set.seed(1) 50 | 51 | x <- ts(rnorm(5000)) 52 | xz <- as.zoo(x) 53 | system.time({ ################################ 54 | for(i in 1:5000) if (is.regular(x)) 55 | x[(i - tsp(x)[1])*frequency(x) + 1] <- 0 56 | else 57 | window(xz, start = i, end = i) <- 0 58 | }, 59 | gc = TRUE) 60 | system.time( for (i in 1:5000) xz[I(i)] <- 0, gc = TRUE ) 61 | system.time( for (i in 1:5000) window(xz, start=i, end=i) <- 0, 62 | gc = TRUE 63 | 64 | o zoo() 65 | - support zoo data.frame objects (and zoo list objects) 66 | - fully support zoo factor objects [limited support already 67 | available] 68 | - idea: new class "Zoo" that is not a matrix plus attribute 69 | but a list with slots "coredata", "index" and "frequency". 70 | 71 | o merge() 72 | - names not processed correctly when retclass = "list" 73 | 74 | o misc functions 75 | - interface to additional statistical routines such as the ones 76 | referenced in: 77 | http://CRAN.R-project.org/doc/contrib/Ricci-refcard-ts.pdf 78 | [Z: with as.ts.zoo() most of the functions work directly 79 | by coercing the first argument to "ts"] 80 | 81 | o QA: regression test suite 82 | 83 | o make.par.list. names, other than correspondence names, are 84 | not allowed on x. Perhaps this should be allowed if m = 1 85 | or perhaps it should be allowed if x is not a list and 86 | correspondence names only allowed for lists. 87 | 88 | o rollapply.default 89 | 90 | o as of lattice 0.12-14 lattice:::updateList could be replaced with 91 | modifyList 92 | 93 | 94 | o read.zoo. The following situations have all appeared on r-help: 95 | - the index is of the form yyyy-mm-dd hh:mm:ss at the beginning of each 96 | line but sep is whitespace. To handle this read.zoo would have to 97 | figure out special cases in which there is whitespace in the 98 | format and use two columsn rather than one. I think it would be 99 | good enough if it only handled a single whitespace. 100 | - header does not have a component corresponding to the index. It 101 | would be nice if read.zoo could automatically figure out that situation 102 | and handle it. 103 | - the date format is yyyy.mm . In that case it would be convenient 104 | if it were possible to specify: 105 | read.zoo(..., FUN = as.yearmon, format = "%Y.%m") 106 | and, in general, if format were passed to FUN if both are specified. 107 | 108 | o identify.zoo 109 | 110 | o allow index.column in read.zoo to be a vector in which case it 111 | pastes them together so that 9999-99-99 99:99:99 99 99 99 112 | can be read directly as dates and times. 113 | 114 | o add class= arg to as.zoo.ts 115 | 116 | o cut/seq/floor/ceiling/round/trunc on yearmon/yearqtr objects 117 | 118 | 119 | INTERFACES 120 | ********** 121 | 122 | o provide fCalendar interface routine to the Rmetrics projects 123 | 124 | 125 | 126 | DOCUMENTATION & COMMUNICATION 127 | ***************************** 128 | 129 | o R news article based on the vignette 130 | 131 | o some data to include with zoo 132 | 133 | o more examples for the help files 134 | 135 | o as of R 2.6.0 the example in aggregate.zoo.Rd that uses 136 | duplicates(..., fromLast=) could be taken out of the \dontrun{} 137 | 138 | -------------------------------------------------------------------------------- /inst/doc/MSFT.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cran/zoo/d032ed0519de3eeefe651ad9f25f7408461732a0/inst/doc/MSFT.rda -------------------------------------------------------------------------------- /inst/doc/demo1.txt: -------------------------------------------------------------------------------- 1 | 10 Feb 2005|43.78 2 | 11 Feb 2005|43.79 3 | 14 Feb 2005|43.72 4 | 15 Feb 2005|43.76 5 | 16 Feb 2005|43.82 6 | 17 Feb 2005|43.74 7 | 18 Feb 2005|43.84 8 | 21 Feb 2005|43.82 9 | 22 Feb 2005|43.72 10 | 23 Feb 2005|43.72 11 | 24 Feb 2005|43.70 12 | 25 Feb 2005|43.69 13 | 28 Feb 2005|43.64 14 | 01 Mar 2005|43.72 15 | 02 Mar 2005|43.70 16 | 03 Mar 2005|43.65 17 | 04 Mar 2005|43.71 18 | 07 Mar 2005|43.69 19 | 09 Mar 2005|43.67 20 | 10 Mar 2005|43.58 21 | -------------------------------------------------------------------------------- /inst/doc/demo2.txt: -------------------------------------------------------------------------------- 1 | Daily,10 Feb 2005,2063.35,4379.20 2 | Daily,11 Feb 2005,2082.05,4382.90 3 | Daily,14 Feb 2005,2098.25,4391.15 4 | Daily,15 Feb 2005,2089.95,4367.25 5 | Daily,17 Feb 2005,2061.90,4320.15 6 | Daily,18 Feb 2005,2055.55,4318.15 7 | Daily,21 Feb 2005,2043.20,4262.25 8 | Daily,22 Feb 2005,2058.40,4326.10 9 | Daily,23 Feb 2005,2057.10,4346.00 10 | Daily,24 Feb 2005,2055.30,4337.00 11 | Daily,25 Feb 2005,2060.90,4305.75 12 | Daily,28 Feb 2005,2103.25,4388.20 13 | Daily,01 Mar 2005,2084.40,4382.25 14 | Daily,02 Mar 2005,2093.25,4470.00 15 | Daily,03 Mar 2005,2128.85,4515.80 16 | Daily,04 Mar 2005,2148.15,4549.55 17 | Daily,07 Mar 2005,2160.10,4618.05 18 | Daily,08 Mar 2005,2168.95,4666.70 19 | Daily,09 Mar 2005,2160.80,4623.85 20 | Daily,10 Mar 2005,2167.40,4648.05 21 | -------------------------------------------------------------------------------- /inst/doc/msft2004.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cran/zoo/d032ed0519de3eeefe651ad9f25f7408461732a0/inst/doc/msft2004.rda -------------------------------------------------------------------------------- /inst/doc/sunw.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cran/zoo/d032ed0519de3eeefe651ad9f25f7408461732a0/inst/doc/sunw.rda -------------------------------------------------------------------------------- /inst/doc/zoo-design.R: -------------------------------------------------------------------------------- 1 | ### R code from vignette source 'zoo-design.Rnw' 2 | 3 | ################################################### 4 | ### code chunk number 1: preliminaries 5 | ################################################### 6 | library("zoo") 7 | Sys.setenv(TZ = "GMT") 8 | 9 | 10 | -------------------------------------------------------------------------------- /inst/doc/zoo-design.Rnw: -------------------------------------------------------------------------------- 1 | \documentclass[article,nojss]{jss} 2 | %% need no \usepackage{Sweave} 3 | 4 | \title{\pkg{zoo} Design} 5 | \Plaintitle{zoo Design} 6 | 7 | \author{\pkg{zoo} Development Team} 8 | \Plainauthor{zoo Development Team} 9 | 10 | \Address{ 11 | \pkg{zoo} Development Team\\ 12 | \proglang{R}-Forge: \url{http://R-Forge.R-project.org/projects/zoo/}\\ 13 | Comprehensive \proglang{R} Archive Network: \url{http://CRAN.R-project.org/package=zoo} 14 | } 15 | 16 | \Keywords{irregular time series, ordered observations, time index} 17 | 18 | \Abstract{ 19 | This is a set of design principles that -- albeit not having been explicitly set out 20 | initially -- have guided the development of the \proglang{R} \pkg{zoo} package. 21 | } 22 | 23 | \begin{document} 24 | 25 | \SweaveOpts{engine=R,eps=FALSE} 26 | %\VignetteIndexEntry{zoo Design} 27 | %\VignetteDepends{zoo} 28 | %\VignetteKeywords{irregular time series, ordered observations, time index} 29 | %\VignettePackage{zoo} 30 | 31 | 32 | <>= 33 | library("zoo") 34 | Sys.setenv(TZ = "GMT") 35 | @ 36 | 37 | \emph{\pkg{zoo} works with any ordered index class} having the prescribed 38 | methods, see \code{?zoo} and \cite{zoo:Zeileis+Grothendieck:2005}. 39 | Specific index classes are not hard-coded in functions (with 40 | a few exceptions necessitated by external interfaces such as reading 41 | and interfacing with `\code{ts}') but rather all index operations are only done 42 | via the allowed methods. 43 | 44 | \emph{\pkg{zoo} is invisible}. As far as possible new names (e.g., for functions or methods 45 | and their arguments) are not introduced. 46 | New functionality is added as methods to generics from base \proglang{R} 47 | allowing reuse of those names. When names are added, thought is put 48 | into the name since \pkg{zoo} is so miserly about adding them. For example, 49 | the \code{read.zoo} name is obviously derived from \code{read.table} and the names 50 | \code{na.locf} or \code{na.approx} are in analogy to other \code{na.*} functions 51 | frome base \proglang{R}. 52 | 53 | \emph{\pkg{zoo} is consistent with base \proglang{R}}. The idea is to make the usage 54 | of \pkg{zoo} completely natural to someone who already has experience with \proglang{R} 55 | (in particular with the `\code{ts}' class). Certainly, \pkg{zoo} contains extensions 56 | to base \proglang{R}, but they should be as consistent as possible and have a natural 57 | `look and feel'. 58 | 59 | \emph{\pkg{zoo} is infrastructure}. \pkg{zoo} tries to do basic things well, e.g., 60 | data reading, handling, aggregation, transformation, etc. However, it does not 61 | provide time series modeling functionality -- \pkg{zoo} rather encourages add-on 62 | packages. A list of current packages employing \pkg{zoo} can be found on the Comprehensive 63 | \proglang{R} Archive Network (CRAN) and in the \pkg{zoo} FAQ, see \code{vignette("zoo-faq", package = "zoo")}. 64 | 65 | \emph{\pkg{zoo} interfaces to all other time series packages} on CRAN (or at 66 | least all of the more popular ones and some of the relatively unknown 67 | ones as well). Thus, time series information can be passed back and forth relatively easily 68 | between `\code{zoo}' and other time series classes and hence combinations of various 69 | functionalities are facilitated. 70 | 71 | \emph{\pkg{zoo} includes extensive documentation}. In addition to the standard \code{help()} 72 | pages, \pkg{zoo} provides a set of vignettes, see \code{vignette(package = "zoo")} for a list. 73 | Furthermore, the \pkg{zoo} Development Team members also post frequently 74 | on the mailing lists (especially ``\proglang{R}-help'', ``\proglang{R}-devel'', and 75 | ``\proglang{R}-SIG-Finance'') whose archives hence contain many useful code snippets etc. 76 | 77 | \emph{\pkg{zoo} has no bug list since all bugs are fixed (almost) immediately}. Over the last 78 | years, \pkg{zoo} has grown into a mature package. Nevertheless, there are always still bugs 79 | (or border cases that are not handled well). When reported to the development team by e-mail, 80 | these typically get fixed immediately in the Subversion (SVN) repository on \proglang{R}-Forge. 81 | (As of this writing, there are a couple of entries in the \pkg{zoo} \proglang{R}-Forge bug list, 82 | however typically this is not the situation.) 83 | 84 | \emph{\pkg{zoo} includes formal regression testing}. We have started developing formal regression 85 | tests employing \proglang{R}'s own system (in \code{zoo/tests/}) as well as the \pkg{RUnit} 86 | package \citep{zoo:RUnit}. 87 | 88 | \bibliography{zoo} 89 | 90 | \end{document} 91 | -------------------------------------------------------------------------------- /inst/doc/zoo-design.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cran/zoo/d032ed0519de3eeefe651ad9f25f7408461732a0/inst/doc/zoo-design.pdf -------------------------------------------------------------------------------- /inst/doc/zoo-faq.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cran/zoo/d032ed0519de3eeefe651ad9f25f7408461732a0/inst/doc/zoo-faq.pdf -------------------------------------------------------------------------------- /inst/doc/zoo-quickref.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cran/zoo/d032ed0519de3eeefe651ad9f25f7408461732a0/inst/doc/zoo-quickref.pdf -------------------------------------------------------------------------------- /inst/doc/zoo-read.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cran/zoo/d032ed0519de3eeefe651ad9f25f7408461732a0/inst/doc/zoo-read.pdf -------------------------------------------------------------------------------- /inst/doc/zoo.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cran/zoo/d032ed0519de3eeefe651ad9f25f7408461732a0/inst/doc/zoo.pdf -------------------------------------------------------------------------------- /inst/include/zoo.h: -------------------------------------------------------------------------------- 1 | /* 2 | Header file for using internal C-level facilities 3 | provided by zoo. 4 | 5 | This is not 100% designed for end users, so 6 | any user comments and bug reports are very 7 | welcomed. 8 | 9 | Copyright Jeffrey A. Ryan 2010 10 | */ 11 | 12 | #include 13 | #include 14 | 15 | #ifndef _Zoo 16 | #define _Zoo 17 | 18 | SEXP zoo_lag (SEXP x, SEXP _k, SEXP _pad); 19 | SEXP zoo_coredata (SEXP x, SEXP copyAttr); 20 | #endif 21 | -------------------------------------------------------------------------------- /man/MATCH.Rd: -------------------------------------------------------------------------------- 1 | \name{MATCH} 2 | \alias{MATCH} 3 | \alias{MATCH.default} 4 | \alias{MATCH.times} 5 | \alias{MATCH.timeDate} 6 | \alias{MATCH.Date} 7 | \alias{MATCH.POSIXct} 8 | \alias{MATCH.POSIXlt} 9 | 10 | \title{Value Matching} 11 | 12 | \description{ 13 | \code{MATCH} is a generic function for value matching. 14 | } 15 | 16 | \usage{ 17 | MATCH(x, table, nomatch = NA, \dots) 18 | \method{MATCH}{times}(x, table, nomatch = NA, units = "sec", eps = 1e-10, \dots) 19 | } 20 | \arguments{ 21 | \item{x}{an object.} 22 | \item{table}{the values to be matched against.} 23 | \item{nomatch}{the value to be returned in the case when no match is 24 | found. Note that it is coerced to \code{integer}.} 25 | \item{units}{See \code{\link[chron]{trunc.times}}.} 26 | \item{eps}{See \code{\link[chron]{trunc.times}}.} 27 | \item{\dots}{further arguments to be passed to methods.} 28 | } 29 | 30 | \details{ 31 | \code{MATCH} is a new generic function which aims at providing 32 | the functionality of the non-generic base function \code{\link[base]{match}} 33 | for arbitrary objects. Currently, there is a default method which 34 | simply calls \code{\link[base]{match}} and various methods for time/date 35 | objects. 36 | 37 | The \code{MATCH} method for \code{Date} objects coerces the \code{table} 38 | to \code{Date} as well (if necessary) and then uses 39 | \code{match(unclass(x), unclass(table), ...}. Similarly, the \code{MATCH} 40 | methods for \code{POSIXct}, \code{POSIXlt}, and \code{timeDate} coerce 41 | both \code{x} and \code{table} to \code{POSIXct} and then match the unclassed 42 | objects. 43 | 44 | \code{MATCH.times} is used for \code{chron} objects. \code{x} will 45 | match any time in \code{table} less than \code{units} away. 46 | } 47 | 48 | 49 | \seealso{\code{\link[base]{match}}} 50 | 51 | \examples{ 52 | MATCH(1:5, 2:3) 53 | } 54 | \keyword{manip} 55 | -------------------------------------------------------------------------------- /man/ORDER.Rd: -------------------------------------------------------------------------------- 1 | \name{ORDER} 2 | \alias{ORDER} 3 | \alias{ORDER.default} 4 | \title{Ordering Permutation} 5 | \description{ 6 | \code{ORDER} is a generic function for computing ordering 7 | permutations. 8 | } 9 | 10 | \usage{ 11 | ORDER(x, \dots) 12 | \method{ORDER}{default}(x, \dots, na.last = TRUE, decreasing = FALSE) 13 | } 14 | \arguments{ 15 | \item{x}{an object.} 16 | \item{\dots}{further arguments to be passed to methods.} 17 | \item{na.last}{for controlling the treatment of \code{NA}s. 18 | If \code{TRUE}, missing values in the data are put last; if 19 | \code{FALSE}, they are put first; if \code{NA}, they are removed. 20 | } 21 | \item{decreasing}{logical. Should the sort order be increasing or 22 | decreasing?} 23 | } 24 | 25 | \details{ 26 | \code{ORDER} is a new generic function which aims at providing 27 | the functionality of the non-generic base function \code{\link[base]{order}} 28 | for arbitrary objects. Currently, there is only a default method which 29 | simply calls \code{\link[base]{order}}. For objects (more precisely if 30 | \code{\link[base]{is.object}} is \code{TRUE}) \code{order} 31 | leverages the generic \code{xtfrm}. Thus, to assure ordering 32 | works, one can supply either a method to \code{xtfrm} or to \code{ORDER} 33 | (or both). 34 | } 35 | 36 | 37 | \seealso{\code{\link[base]{order}}} 38 | 39 | \examples{ 40 | ORDER(rnorm(5)) 41 | } 42 | \keyword{manip} 43 | -------------------------------------------------------------------------------- /man/aggregate.zoo.Rd: -------------------------------------------------------------------------------- 1 | 2 | \name{aggregate.zoo} 3 | \alias{aggregate.zoo} 4 | \alias{split.zoo} 5 | \title{Compute Summary Statistics of zoo Objects} 6 | \description{ 7 | Splits a \code{"zoo"} object into subsets along a coarser index grid, 8 | computes summary statistics for each, and returns the 9 | reduced \code{"zoo"} object. 10 | } 11 | 12 | \usage{ 13 | \method{aggregate}{zoo}(x, by, FUN = sum, \dots, 14 | regular = NULL, frequency = NULL, coredata = TRUE) 15 | } 16 | 17 | \arguments{ 18 | \item{x}{an object of class \code{"zoo"}.} 19 | \item{by}{index vector of the same length as \code{index(x)} which defines 20 | aggregation groups and the new index to be associated with each group. 21 | If \code{by} is a function, then it is applied to \code{index(x)} to 22 | obtain the aggregation groups.} 23 | \item{FUN}{a function to compute the summary statistics which can be applied 24 | to all subsets. Always needs to return a result of fixed length (typically 25 | scalar).} 26 | \item{\dots}{further arguments passed to \code{FUN}.} 27 | \item{regular}{logical. Should the aggregated series be coerced to class \code{"zooreg"} 28 | (if the series is regular)? The default is \code{FALSE} for \code{"zoo"} series and 29 | \code{TRUE} for \code{"zooreg"} series.} 30 | \item{frequency}{numeric indicating the frequency of the aggregated series 31 | (if a \code{"zooreg"} series should be returned. The default is to 32 | determine the frequency from the data if \code{regular} is \code{TRUE}. 33 | If \code{frequency} is specified, it sets \code{regular} to \code{TRUE}. 34 | See examples for illustration.} 35 | \item{coredata}{logical. Should only the \code{coredata(x)} 36 | be passed to every \code{by} group? If set to \code{FALSE} the 37 | full zoo series is used.} 38 | } 39 | 40 | \value{ 41 | An object of class \code{"zoo"} or \code{"zooreg"}. 42 | } 43 | 44 | \note{The \code{xts} package functions \code{endpoints}, \code{period.apply} 45 | \code{to.period}, \code{to.weekly}, \code{to.monthly}, etc., 46 | can also directly input and output certain \code{zoo} objects and 47 | so can be used for aggregation tasks in some cases as well.} 48 | 49 | \seealso{\code{\link{zoo}}} 50 | 51 | \examples{ 52 | ## averaging over values in a month: 53 | # x.date is jan 1,3,5,7; feb 9,11,13; mar 15,17,19 54 | x.date <- as.Date(paste(2004, rep(1:4, 4:1), seq(1,20,2), sep = "-")); x.date 55 | x <- zoo(rnorm(12), x.date); x 56 | # coarser dates - jan 1 (4 times), feb 1 (3 times), mar 1 (3 times) 57 | x.date2 <- as.Date(paste(2004, rep(1:4, 4:1), 1, sep = "-")); x.date2 58 | x2 <- aggregate(x, x.date2, mean); x2 59 | # same - uses as.yearmon 60 | x2a <- aggregate(x, as.Date(as.yearmon(time(x))), mean); x2a 61 | # same - uses by function 62 | x2b <- aggregate(x, function(tt) as.Date(as.yearmon(tt)), mean); x2b 63 | # same - uses cut 64 | x2c <- aggregate(x, as.Date(cut(time(x), "month")), mean); x2c 65 | # almost same but times of x2d have yearmon class rather than Date class 66 | x2d <- aggregate(x, as.yearmon, mean); x2d 67 | 68 | # compare time series 69 | plot(x) 70 | lines(x2, col = 2) 71 | 72 | ## aggregate a daily time series to a quarterly series 73 | # create zoo series 74 | tt <- as.Date("2000-1-1") + 0:300 75 | z.day <- zoo(0:300, tt) 76 | 77 | # function which returns corresponding first "Date" of quarter 78 | first.of.quarter <- function(tt) as.Date(as.yearqtr(tt)) 79 | 80 | # average z over quarters 81 | # 1. via "yearqtr" index (regular) 82 | # 2. via "Date" index (not regular) 83 | z.qtr1 <- aggregate(z.day, as.yearqtr, mean) 84 | z.qtr2 <- aggregate(z.day, first.of.quarter, mean) 85 | 86 | # The last one used the first day of the quarter but suppose 87 | # we want the first day of the quarter that exists in the series 88 | # (and the series does not necessarily start on the first day 89 | # of the quarter). 90 | z.day[!duplicated(as.yearqtr(time(z.day)))] 91 | 92 | # This is the same except it uses the last day of the quarter. 93 | # It requires R 2.6.0 which introduced the fromLast= argument. 94 | \dontrun{ 95 | z.day[!duplicated(as.yearqtr(time(z.day)), fromLast = TRUE)] 96 | } 97 | 98 | # The aggregated series above are of class "zoo" (because z.day 99 | # was "zoo"). To create a regular series of class "zooreg", 100 | # the frequency can be automatically chosen 101 | zr.qtr1 <- aggregate(z.day, as.yearqtr, mean, regular = TRUE) 102 | # or specified explicitely 103 | zr.qtr2 <- aggregate(z.day, as.yearqtr, mean, frequency = 4) 104 | 105 | 106 | ## aggregate on month and extend to monthly time series 107 | if(require(chron)) { 108 | y <- zoo(matrix(11:15, nrow = 5, ncol = 2), chron(c(15, 20, 80, 100, 110))) 109 | colnames(y) <- c("A", "B") 110 | 111 | # aggregate by month using first of month as times for coarser series 112 | # using first day of month as repesentative time 113 | y2 <- aggregate(y, as.Date(as.yearmon(time(y))), head, 1) 114 | 115 | # fill in missing months by merging with an empty series containing 116 | # a complete set of 1st of the months 117 | yrt2 <- range(time(y2)) 118 | y0 <- zoo(,seq(from = yrt2[1], to = yrt2[2], by = "month")) 119 | merge(y2, y0) 120 | } 121 | 122 | # given daily series keep only first point in each month at 123 | # day 21 or more 124 | z <- zoo(101:200, as.Date("2000-01-01") + seq(0, length = 100, by = 2)) 125 | zz <- z[as.numeric(format(time(z), "\%d")) >= 21] 126 | zz[!duplicated(as.yearmon(time(zz)))] 127 | 128 | # same except times are of "yearmon" class 129 | aggregate(zz, as.yearmon, head, 1) 130 | 131 | # aggregate POSIXct seconds data every 10 minutes 132 | Sys.setenv(TZ = "GMT") 133 | tt <- seq(10, 2000, 10) 134 | x <- zoo(tt, structure(tt, class = c("POSIXt", "POSIXct"))) 135 | aggregate(x, time(x) - as.numeric(time(x)) \%\% 600, mean) 136 | 137 | # aggregate weekly series to a series with frequency of 52 per year 138 | suppressWarnings(RNGversion("3.5.0")) 139 | set.seed(1) 140 | z <- zooreg(1:100 + rnorm(100), start = as.Date("2001-01-01"), deltat = 7) 141 | 142 | # new.freq() converts dates to a grid of freq points per year 143 | # yd is sequence of dates of firsts of years 144 | # yy is years of the same sequence 145 | # last line interpolates so dates, d, are transformed to year + frac of year 146 | # so first week of 2001 is 2001.0, second week is 2001 + 1/52, third week 147 | # is 2001 + 2/52, etc. 148 | new.freq <- function(d, freq = 52) { 149 | y <- as.Date(cut(range(d), "years")) + c(0, 367) 150 | yd <- seq(y[1], y[2], "year") 151 | yy <- as.numeric(format(yd, "\%Y")) 152 | floor(freq * approx(yd, yy, xout = d)$y) / freq 153 | } 154 | 155 | # take last point in each period 156 | aggregate(z, new.freq, tail, 1) 157 | 158 | # or, take mean of all points in each 159 | aggregate(z, new.freq, mean) 160 | 161 | # example of taking means in the presence of NAs 162 | z.na <- zooreg(c(1:364, NA), start = as.Date("2001-01-01")) 163 | aggregate(z.na, as.yearqtr, mean, na.rm = TRUE) 164 | 165 | # Find the sd of all days that lie in any Jan, all days that lie in 166 | # any Feb, ..., all days that lie in any Dec (i.e. output is vector with 167 | # 12 components) 168 | aggregate(z, format(time(z), "\%m"), sd) 169 | 170 | } 171 | \keyword{ts} 172 | -------------------------------------------------------------------------------- /man/as.zoo.Rd: -------------------------------------------------------------------------------- 1 | \name{as.zoo} 2 | \alias{as.zoo} 3 | \alias{as.zoo.default} 4 | \alias{as.zoo.data.frame} 5 | \alias{as.zoo.fts} 6 | \alias{as.zoo.its} 7 | \alias{as.zoo.irts} 8 | \alias{as.zoo.matrix} 9 | \alias{as.zoo.mcmc} 10 | \alias{as.zoo.tis} 11 | \alias{as.zoo.xts} 12 | \alias{as.zoo.zoo} 13 | \alias{as.matrix.zoo} 14 | \alias{as.vector.zoo} 15 | \alias{as.data.frame.zoo} 16 | \alias{as.list.zoo} 17 | \alias{as.list.ts} 18 | \alias{as.zoo.ts} 19 | \alias{as.ts.zoo} 20 | 21 | \title{Coercion from and to zoo} 22 | \description{ 23 | Methods for coercing \code{"zoo"} objects to other classes and 24 | a generic function \code{as.zoo} for coercing objects to class \code{"zoo"}. 25 | } 26 | \usage{ 27 | as.zoo(x, \dots) 28 | } 29 | \arguments{ 30 | \item{x}{an object,} 31 | \item{\dots}{further arguments passed to \code{\link{zoo}} when the return 32 | object is created.} 33 | } 34 | 35 | \details{ 36 | \code{as.zoo} currently has a default method and methods for \code{\link{ts}}, 37 | \code{fts} (currently archived on CRAN), \code{\link[tseries]{irts}}, 38 | \code{\link[coda]{mcmc}}, \code{\link[tis]{tis}}, \code{\link[xts]{xts}} 39 | objects (and \code{\link{zoo}} objects themselves). 40 | 41 | Methods for coercing objects of class \code{"zoo"} to other classes 42 | currently include: \code{\link{as.ts}}, \code{\link{as.matrix}}, \code{\link{as.vector}}, 43 | \code{\link{as.data.frame}}, \code{\link{as.list}} (the latter also being available 44 | for \code{"ts"} objects). Furthermore, \code{\link{fortify.zoo}} can transform \code{"zoo"} 45 | series to \code{"data.frame"} including the time index and optionally melting a wide series 46 | into a long data frame. 47 | 48 | In the conversion between \code{zoo} and \code{ts}, the \code{\link{zooreg}} class is 49 | always used. 50 | } 51 | 52 | \value{ 53 | \code{as.zoo} returns a \code{\link{zoo}} object. 54 | } 55 | 56 | \seealso{\code{\link{zoo}}, \code{\link{fortify.zoo}}, 57 | \code{\link{zooreg}}, \code{\link{ts}}, \code{\link[tseries]{irts}}, 58 | \code{\link[tis]{tis}}, \code{\link[coda]{mcmc}}, 59 | \code{\link[xts]{xts}}. 60 | } 61 | 62 | \examples{ 63 | suppressWarnings(RNGversion("3.5.0")) 64 | set.seed(1) 65 | 66 | ## coercion to zoo: 67 | ## default method 68 | as.zoo(rnorm(5)) 69 | ## method for "ts" objects 70 | as.zoo(ts(rnorm(5), start = 1981, freq = 12)) 71 | 72 | ## coercion from zoo: 73 | x.date <- as.POSIXct(paste("2003-", rep(1:4, 4:1), "-", sample(1:28, 10, replace = TRUE), sep = "")) 74 | x <- zoo(matrix(rnorm(24), ncol = 2), x.date) 75 | as.matrix(x) 76 | as.vector(x) 77 | as.data.frame(x) 78 | as.list(x) 79 | } 80 | \keyword{ts} 81 | -------------------------------------------------------------------------------- /man/coredata.Rd: -------------------------------------------------------------------------------- 1 | \name{coredata} 2 | \alias{coredata} 3 | \alias{coredata.default} 4 | \alias{coredata.zoo} 5 | \alias{coredata.ts} 6 | \alias{coredata.its} 7 | \alias{coredata.irts} 8 | \alias{coredata<-} 9 | \alias{coredata<-.zoo} 10 | \alias{coredata<-.ts} 11 | \alias{coredata<-.irts} 12 | \alias{coredata<-.its} 13 | \title{Extracting/Replacing the Core Data of Objects} 14 | \description{ 15 | Generic functions for extracting the core data contained in 16 | a (more complex) object and replacing it. 17 | } 18 | 19 | \usage{ 20 | coredata(x, \dots) 21 | coredata(x) <- value 22 | } 23 | 24 | \arguments{ 25 | \item{x}{an object.} 26 | \item{\dots}{further arguments passed to methods.} 27 | \item{value}{a suitable value object for use with \code{x}.} 28 | } 29 | 30 | \value{ 31 | In \code{zoo}, there are currently \code{coredata} methods for time series 32 | objects of class \code{"zoo"}, \code{"ts"}, \code{"its"}, \code{"irts"}, all of 33 | which strip off the index/time attributes and return only the observations. 34 | The are also corresponding replacement methods for these classes. 35 | } 36 | 37 | \seealso{\code{\link{zoo}}} 38 | 39 | \examples{ 40 | suppressWarnings(RNGversion("3.5.0")) 41 | set.seed(1) 42 | 43 | x.date <- as.Date(paste(2003, rep(1:4, 4:1), seq(1,20,2), sep = "-")) 44 | x <- zoo(matrix(rnorm(20), ncol = 2), x.date) 45 | 46 | ## the full time series 47 | x 48 | ## and only matrix of observations 49 | coredata(x) 50 | 51 | ## change the observations 52 | coredata(x) <- matrix(1:20, ncol = 2) 53 | x 54 | } 55 | \keyword{ts} 56 | -------------------------------------------------------------------------------- /man/frequency.Rd: -------------------------------------------------------------------------------- 1 | \name{frequency<-} 2 | \alias{frequency<-} 3 | \alias{frequency<-.zoo} 4 | \alias{frequency<-.zooreg} 5 | \title{Replacing the Index of Objects} 6 | \description{ 7 | Generic function for replacing the frequency of an object. 8 | } 9 | \usage{ 10 | frequency(x) <- value 11 | } 12 | \arguments{ 13 | \item{x}{an object.} 14 | \item{value}{a frequency.} 15 | } 16 | 17 | \details{ 18 | \code{frequency<-} is a generic function for replacing (or assigning) 19 | the frequency of an object. Currently, there is a \code{"zooreg"} and 20 | a \code{"zoo"} method. In both cases, the \code{value} is assigned 21 | to the \code{"frequency"} of the object if it complies with the 22 | \code{index(x)}. 23 | } 24 | 25 | \seealso{\code{\link{zooreg}}, \code{\link{index}}} 26 | 27 | \examples{ 28 | z <- zooreg(1:5) 29 | z 30 | as.ts(z) 31 | frequency(z) <- 3 32 | z 33 | as.ts(z) 34 | } 35 | \keyword{ts} 36 | -------------------------------------------------------------------------------- /man/ggplot2.zoo.Rd: -------------------------------------------------------------------------------- 1 | \name{ggplot2.zoo} 2 | \alias{autoplot.zoo} 3 | \alias{fortify.zoo} 4 | \alias{ggplot2.zoo} 5 | \alias{facet_free} 6 | \alias{yearmon_trans} 7 | \alias{yearqtr_trans} 8 | \alias{scale_x_yearmon} 9 | \alias{scale_y_yearmon} 10 | \alias{scale_x_yearqtr} 11 | \alias{scale_y_yearqtr} 12 | \alias{scale_type.yearmon} 13 | \alias{scale_type.yearqtr} 14 | 15 | \title{Convenience Functions for Plotting zoo Objects with ggplot2} 16 | 17 | \details{ 18 | Convenience interface for visualizing zoo objects with ggplot2. 19 | \code{autoplot.zoo} uses \code{fortify.zoo} (with \code{melt = TRUE}) 20 | to convert the zoo object into a data frame and then uses a suitable 21 | \code{aes()} mapping to visiualize the series. 22 | } 23 | 24 | \usage{ 25 | \method{autoplot}{zoo}(object, geom = "line", facets, \dots) 26 | \method{fortify}{zoo}(model, data, 27 | names = c("Index", "Series", "Value"), 28 | melt = FALSE, sep = NULL, \dots) 29 | facet_free(facets = Series ~ ., margins = FALSE, scales = "free_y", \dots) 30 | 31 | yearmon_trans(format = "\%b \%Y", n = 5) 32 | scale_x_yearmon(\dots, format = "\%b \%Y", n = 5) 33 | scale_y_yearmon(\dots, format = "\%b \%Y", n = 5) 34 | 35 | yearqtr_trans(format = "\%Y-\%q", n = 5) 36 | scale_x_yearqtr(\dots, format = "\%Y-\%q", n = 5) 37 | scale_y_yearqtr(\dots, format = "\%Y-\%q", n = 5) 38 | } 39 | 40 | \arguments{ 41 | \item{object}{an object of class \code{"zoo"}.} 42 | \item{geom}{character (e.g., \code{"line"}) or function (e.g., \code{\link[ggplot2]{geom_line}}) 43 | specifying which \code{geom} to use.} 44 | \item{facets}{specification of \code{facets} for \code{\link[ggplot2]{facet_grid}}. The 45 | default in the \code{autoplot} method is to use \code{facets = NULL} for univariate 46 | series and \code{facets = Series ~ .} for multivariate series.} 47 | \item{\dots}{further arguments passed to \code{\link[ggplot2]{aes}} 48 | for \code{autoplot} (e.g., \code{linetype = Series} and/or \code{shape = Series}). 49 | For \code{fortify} the arguments are not used. For the \code{scale_*_*} 50 | functions the arguments are passed on to \code{scale_*_continuous}.} 51 | \item{model}{an object of class \code{"zoo"} to be converted to 52 | a \code{"data.frame"}.} 53 | \item{data}{not used (required by generic \code{\link[ggplot2]{fortify}} 54 | method).} 55 | \item{names}{(list of) character vector(s). New names given to index/time column, 56 | series indicator (if melted), and value column (if melted). If only 57 | a subset of characters should be changed, either NAs can be used 58 | or a named vector.} 59 | \item{sep}{If specified then the Series column is split into multiple 60 | columns using sep as the split character.} 61 | \item{melt}{Should the resulting data frame be in long format (\code{melt = TRUE}) 62 | or wide format (\code{melt = FALSE}).} 63 | \item{margins}{As in \code{\link[ggplot2]{facet_grid}}.} 64 | \item{scales}{As in \code{\link[ggplot2]{facet_grid}} except it defaults to \code{"free_y"}.} 65 | \item{format}{A format acceptable to \link{format.yearmon} or \link{format.yearqtr}.} 66 | \item{n}{Approximate number of axis ticks.} 67 | } 68 | 69 | \description{ 70 | \code{fortify.zoo} takes a zoo object and converts it into a data frame 71 | (intended for ggplot2). \code{autoplot.zoo} takes a zoo object and returns a 72 | ggplot2 object. It essentially uses the mapping \code{aes(x = Time, y = Value, group = Series)} 73 | and adds \code{colour = Series} in the case of a multivariate series with \code{facets = NULL}. 74 | } 75 | 76 | \value{ 77 | \code{fortify.zoo} returns a \code{data.frame} either in long format 78 | (\code{melt = TRUE}) or in wide format (\code{melt = FALSE}). The 79 | long format has three columns: the time \code{Index}, a 80 | factor indicating the \code{Series}, and the corresponding \code{Value}. 81 | The wide format simply has the time \code{Index} plus all columns 82 | of \code{coredata(model)}. 83 | 84 | \code{autoplot.zoo} returns a \code{ggplot} object. 85 | } 86 | 87 | \author{ 88 | Trevor L. Davis \email{trevor.l.davis@gmail.com}, Achim Zeileis 89 | } 90 | 91 | \seealso{ 92 | \code{\link[ggplot2]{autoplot}}, \code{\link[ggplot2]{fortify}}, \code{\link[ggplot2]{ggplot}} 93 | } 94 | 95 | \examples{ 96 | if(require("ggplot2") && require("scales")) { 97 | suppressWarnings(RNGversion("3.5.0")) 98 | set.seed(1) 99 | 100 | ## example data 101 | x.Date <- as.Date(paste(2003, 02, c(1, 3, 7, 9, 14), sep = "-")) 102 | x <- zoo(rnorm(5), x.Date) 103 | xlow <- x - runif(5) 104 | xhigh <- x + runif(5) 105 | z <- cbind(x, xlow, xhigh) 106 | 107 | ## univariate plotting 108 | autoplot(x) 109 | ## by hand 110 | ggplot(aes(x = Index, y = Value), data = fortify(x, melt = TRUE)) + 111 | geom_line() + xlab("Index") + ylab("x") 112 | ## adding series one at a time 113 | last_plot() + geom_line(aes(x = Index, y = xlow), colour = "red", data = fortify(xlow)) 114 | ## add ribbon for high/low band 115 | ggplot(aes(x = Index, y = x, ymin = xlow, ymax = xhigh), data = fortify(x)) + 116 | geom_ribbon(fill = "darkgray") + geom_line() 117 | 118 | ## multivariate plotting in multiple or single panels 119 | autoplot(z) ## multiple without color/linetype 120 | autoplot(z, facets = Series ~ .) ## multiple with series-dependent color/linetype 121 | autoplot(z, facets = NULL) ## single with series-dependent color/linetype 122 | ## by hand with color/linetype and with/without facets 123 | ggz <- ggplot(aes(x = Index, y = Value, group = Series, colour = Series, linetype = Series), 124 | data = fortify(z, melt = TRUE)) + geom_line() + xlab("Index") + ylab("") 125 | ggz 126 | ggz + facet_grid(Series ~ .) 127 | ## variations 128 | autoplot(z, geom = "point") 129 | autoplot(z, facets = NULL) + geom_point() 130 | autoplot(z, facets = NULL) + scale_colour_grey() + theme_bw() 131 | 132 | ## for "ts" series via coercion 133 | autoplot(as.zoo(EuStockMarkets)) 134 | autoplot(as.zoo(EuStockMarkets), facets = NULL) 135 | 136 | autoplot(z) + 137 | aes(colour = NULL, linetype = NULL) + 138 | facet_grid(Series ~ ., scales = "free_y") 139 | 140 | autoplot(z) + aes(colour = NULL, linetype = NULL) + facet_free() # same 141 | 142 | z.yq <- zooreg(rnorm(50), as.yearqtr("2000-1"), freq = 4) 143 | autoplot(z.yq) 144 | 145 | ## mimic matplot 146 | data <- cbind(A = c(6, 1, NA, NA), B = c(16, 4, 1, NA), C = c(25, 7, 2, 1)) 147 | autoplot(zoo(data), facet = NULL) + geom_point() 148 | ## with different line types 149 | autoplot(zoo(data), facet = NULL) + geom_point() + aes(linetype = Series) 150 | 151 | ## illustrate just fortify() method 152 | z <- zoo(data) 153 | fortify(z) 154 | fortify(z, melt = TRUE) 155 | fortify(z, melt = TRUE, names = c("Time", NA, "Data")) 156 | fortify(z, melt = TRUE, names = c(Index = "Time")) 157 | 158 | ## with/without splitting 159 | z <- zoo(cbind(a.A = 1:2, a.B = 2:3, b.A = 3:4, c.B = 4:5)) 160 | fortify(z) 161 | fortify(z, melt = TRUE, sep = ".", names = list(Series = c("Lower", "Upper"))) 162 | 163 | ## scale_x_yearmon with custom discrete breaks 164 | df <- data.frame(dates = as.yearmon("2018-08") + 0:6/12, values = c(2:6, 0, 1)) 165 | ggdf <- ggplot(df, aes(x = dates, y = values)) + 166 | geom_bar(position = "dodge", stat = "identity") + theme_light() + 167 | xlab("Month") + ylab("Values") 168 | ggdf ## with default scale_x_yearmon 169 | ggdf + scale_x_yearmon(breaks = df$dates) ## with custom discrete breaks 170 | } 171 | } 172 | 173 | -------------------------------------------------------------------------------- /man/index.Rd: -------------------------------------------------------------------------------- 1 | \name{index} 2 | \alias{index} 3 | \alias{index.default} 4 | \alias{index.zoo} 5 | \alias{index.ts} 6 | \alias{time.zoo} 7 | \alias{index<-} 8 | \alias{index<-.zoo} 9 | \alias{time<-} 10 | \alias{time<-.zoo} 11 | \alias{start.zoo} 12 | \alias{end.zoo} 13 | \title{Extracting/Replacing the Index of Objects} 14 | \description{ 15 | Generic functions for extracting the index of an object 16 | and replacing it. 17 | } 18 | \usage{ 19 | index(x, \dots) 20 | index(x) <- value 21 | } 22 | \arguments{ 23 | \item{x}{an object.} 24 | \item{\dots}{further arguments passed to methods.} 25 | \item{value}{an ordered vector of the same length 26 | as the \code{"index"} attribute of \code{x}.} 27 | } 28 | 29 | \details{ 30 | \code{index} is a generic function for extracting the index 31 | of objects, currently it has a default method and a method 32 | for \code{\link{zoo}} objects which is the same as the 33 | \code{\link{time}} method for \code{\link{zoo}} objects. 34 | Another pair of generic functions provides replacing 35 | the \code{index} or \code{time} attribute. 36 | Methods are available for \code{"zoo"} objects only, see examples below. 37 | 38 | The start and end of the index/time can be queried by using 39 | the methods of \code{start} and \code{end}. 40 | } 41 | 42 | \seealso{\code{\link{time}}, \code{\link{zoo}}} 43 | 44 | \examples{ 45 | suppressWarnings(RNGversion("3.5.0")) 46 | set.seed(1) 47 | 48 | x.date <- as.Date(paste(2003, 2, c(1, 3, 7, 9, 14), sep = "-")) 49 | x <- zoo(rnorm(5), x.date) 50 | 51 | ## query index/time of a zoo object 52 | index(x) 53 | time(x) 54 | 55 | ## change class of index from Date to POSIXct 56 | ## relative to current time zone 57 | x 58 | index(x) <- as.POSIXct(format(time(x)),tz="") 59 | x 60 | 61 | ## replace index/time of a zoo object 62 | index(x) <- 1:5 63 | x 64 | time(x) <- 6:10 65 | x 66 | 67 | ## query start and end of a zoo object 68 | start(x) 69 | end(x) 70 | 71 | ## query index of a usual matrix 72 | xm <- matrix(rnorm(10), ncol = 2) 73 | index(xm) 74 | } 75 | \keyword{ts} 76 | -------------------------------------------------------------------------------- /man/is.regular.Rd: -------------------------------------------------------------------------------- 1 | \name{is.regular} 2 | \alias{is.regular} 3 | \alias{is.regular.zoo} 4 | \alias{is.regular.ts} 5 | \alias{is.regular.zooreg} 6 | \alias{is.regular.default} 7 | 8 | \title{Check Regularity of a Series} 9 | 10 | \description{ 11 | \code{is.regular} is a regular function for checking whether a series of ordered observations 12 | has an underlying regularity or is even strictly regular. 13 | } 14 | 15 | \usage{ 16 | is.regular(x, strict = FALSE) 17 | } 18 | 19 | \arguments{ 20 | \item{x}{an object (representing a series of ordered observations).} 21 | \item{strict}{logical. Should strict regularity be checked? See details.} 22 | } 23 | 24 | \details{ 25 | A time series can either be irregular (unequally spaced), strictly regular (equally spaced) 26 | or have an underlying regularity, i.e., be created from a regular series by 27 | omitting some observations. Here, the latter property is called \emph{regular}. 28 | Consequently, regularity follows from strict regularity but not vice versa. 29 | 30 | \code{is.regular} is a generic function for checking regularity (default) or 31 | strict regularity. Currently, it has methods for \code{"ts"} objects (which are 32 | always strictly regular), \code{"zooreg"} objects (which are at least regular), 33 | \code{"zoo"} objects (which can be either irregular, regular or even strictly regular) 34 | and a default method. The latter coerces \code{x} to \code{"zoo"} before checking 35 | its regularity. 36 | } 37 | 38 | \value{ 39 | A logical is returned indicating whether \code{x} is (strictly) regular. 40 | } 41 | 42 | \seealso{\code{\link{zooreg}}, \code{\link{zoo}}} 43 | 44 | \examples{ 45 | ## checking of a strictly regular zoo series 46 | z <- zoo(1:10, seq(2000, 2002.25, by = 0.25), frequency = 4) 47 | z 48 | class(z) 49 | frequency(z) ## extraction of frequency attribute 50 | is.regular(z) 51 | is.regular(z, strict = TRUE) 52 | ## by omitting observations, the series is not strictly regular 53 | is.regular(z[-3]) 54 | is.regular(z[-3], strict = TRUE) 55 | 56 | ## checking of a plain zoo series without frequency attribute 57 | ## which is in fact regular 58 | z <- zoo(1:10, seq(2000, 2002.25, by = 0.25)) 59 | z 60 | class(z) 61 | frequency(z) ## data driven computation of frequency 62 | is.regular(z) 63 | is.regular(z, strict = TRUE) 64 | ## by omitting observations, the series is not strictly regular 65 | is.regular(z[-3]) 66 | is.regular(z[-3], strict = TRUE) 67 | 68 | suppressWarnings(RNGversion("3.5.0")) 69 | set.seed(1) 70 | 71 | ## checking of an irregular zoo series 72 | z <- zoo(1:10, rnorm(10)) 73 | z 74 | class(z) 75 | frequency(z) ## attempt of data-driven frequency computation 76 | is.regular(z) 77 | is.regular(z, strict = TRUE) 78 | } 79 | \keyword{ts} 80 | -------------------------------------------------------------------------------- /man/lag.zoo.Rd: -------------------------------------------------------------------------------- 1 | \name{lag.zoo} 2 | \alias{lag.zoo} 3 | \alias{diff.zoo} 4 | \title{Lags and Differences of zoo Objects} 5 | \description{ 6 | Methods for computing lags and differences of \code{"zoo"} objects. 7 | } 8 | 9 | \usage{ 10 | \method{lag}{zoo}(x, k = 1, na.pad = FALSE, \dots) 11 | \method{diff}{zoo}(x, lag = 1, differences = 1, arithmetic = TRUE, na.pad = FALSE, log = FALSE, \dots) 12 | } 13 | 14 | \arguments{ 15 | \item{x}{a \code{"zoo"} object.} 16 | \item{k, lag}{For \code{lag} the number of lags (in units of observations). 17 | Note the sign of \code{k} behaves as in \code{\link[stats]{lag}}. 18 | For \code{diff} it is the number of backward lags used (or if negative the 19 | number of forward lags.} 20 | \item{differences}{an integer indicating the order of the difference.} 21 | \item{arithmetic}{logical. Should arithmetic (or geometric) differences be computed?} 22 | \item{na.pad}{logical. If \code{TRUE} it adds any times that would not otherwise have been in 23 | the result with a value of \code{NA}. If \code{FALSE} those times are dropped.} 24 | \item{log}{logical. Should the differences of the log series be computed?} 25 | \item{\dots}{currently not used.} 26 | } 27 | 28 | \details{ 29 | These methods for \code{"zoo"} objects behave analogously to the default 30 | methods. The only additional arguments are \code{arithmetic} and \code{log} in \code{diff} 31 | and \code{na.pad} in both \code{lag.zoo} and \code{diff.zoo}. 32 | Also, \code{"k"} can be a vector of lags in which case the names of 33 | \code{"k"}, if any, are used in naming the result. 34 | 35 | 36 | } 37 | 38 | \value{ 39 | The lagged or differenced \code{"zoo"} object. 40 | } 41 | 42 | 43 | \note{ 44 | Note the sign of \code{k}: a series lagged by a positive \code{k} 45 | is shifted \emph{earlier} in time. 46 | 47 | \code{lag.zoo} and \code{lag.zooreg} can give different results. 48 | For a lag of 1 \code{lag.zoo} moves points to the adjacent time point 49 | whereas \code{lag.zooreg} moves the time by \code{deltat}. This 50 | implies that a point in a \code{zoo} series cannot be lagged to a time 51 | point that is not already in the series whereas this is possible for 52 | a \code{zooreg} series. 53 | } 54 | 55 | 56 | \seealso{\code{\link{zoo}}, \code{\link[stats]{lag}}, \code{\link[base]{diff}}} 57 | 58 | \examples{ 59 | x <- zoo(11:21) 60 | 61 | lag(x, k = 1) 62 | lag(x, k = -1) 63 | # this pairs each value of x with the next or future value 64 | merge(x, lag1 = lag(x, k=1)) 65 | diff(x^3) 66 | diff(x^3, -1) 67 | diff(x^3, na.pad = TRUE) 68 | 69 | } 70 | \keyword{ts} 71 | -------------------------------------------------------------------------------- /man/make.par.list.Rd: -------------------------------------------------------------------------------- 1 | \name{make.par.list} 2 | \alias{make.par.list} 3 | 4 | \title{Make a List from a Parameter Specification} 5 | 6 | \description{ 7 | Process parameters so that a list of parameter 8 | specifications is returned (used by \code{plot.zoo} and 9 | \code{xyplot.zoo}). 10 | } 11 | 12 | \usage{ 13 | make.par.list(nams, x, n, m, def, recycle = sum(unnamed) > 0) 14 | } 15 | 16 | \arguments{ 17 | \item{nams}{character vector with names of variables.} 18 | \item{x}{list or vector of parameter specifications, see details.} 19 | \item{n}{numeric, number of rows.} 20 | \item{m}{numeric, number of columns. (Only determines whether \code{m} 21 | is 1 or greater than 1.} 22 | \item{def}{default parameter value.} 23 | \item{recycle}{logical. If \code{TRUE} recycle columns to provide 24 | unspecified ones. If \code{FALSE} use \code{def} to provide unspecified 25 | ones. This only applies to entire columns. Within columns recycling is 26 | always done regardless of how \code{recycle} is set. Defaults to 27 | \code{TRUE} if there is at least one unnamed variable and defaults to 28 | \code{FALSE} if there are only named variables in \code{x}.} 29 | } 30 | 31 | \details{ 32 | This function is currently intended for internal use. It is currently 33 | used by 34 | \code{plot.zoo} and \code{xyplot.zoo} but might also be used in the future 35 | to create additional new plotting routines. 36 | It creates a new list which uses the named variables from \code{x} 37 | and then assigns the unnamed in order. For the remaining variables 38 | assign them the default value if \code{!recycle} or recycle the 39 | unnamed variables if \code{recycle}. 40 | } 41 | 42 | \value{ 43 | A list of parameters, see details. 44 | } 45 | 46 | \examples{ 47 | make.par.list(letters[1:5], 1:5, 3, 5) 48 | suppressWarnings( make.par.list(letters[1:5], 1:4, 3, 5, 99) ) 49 | make.par.list(letters[1:5], c(d=3), 3, 5, 99) 50 | make.par.list(letters[1:5], list(d=1:2, 99), 3, 5) 51 | make.par.list(letters[1:5], list(d=1:2, 99, 100), 3, 5) 52 | } 53 | 54 | \keyword{ts} 55 | -------------------------------------------------------------------------------- /man/merge.zoo.Rd: -------------------------------------------------------------------------------- 1 | \name{merge.zoo} 2 | \alias{merge.zoo} 3 | \alias{rbind.zoo} 4 | \alias{c.zoo} 5 | \alias{cbind.zoo} 6 | \title{Merge Two or More zoo Objects} 7 | \description{ 8 | Merge two zoo objects by common indexes (times), or do other 9 | versions of database \emph{join} operations. 10 | } 11 | 12 | \usage{ 13 | \method{merge}{zoo}(\dots, all = TRUE, fill = NA, suffixes = NULL, 14 | check.names = FALSE, retclass = c("zoo", "list", "data.frame"), 15 | drop = TRUE, sep = ".") 16 | } 17 | 18 | \arguments{ 19 | \item{\dots}{two or more objects, usually of class \code{"zoo"}.} 20 | \item{all}{logical vector having the same length as the number of \code{"zoo"} 21 | objects to be merged (otherwise expanded).} 22 | \item{fill}{an element for filling gaps in merged \code{"zoo"} 23 | objects (if any).} 24 | \item{suffixes}{character vector of the same length as the number of 25 | \code{"zoo"} objects specifying the suffixes to be used for making 26 | the merged column names unique.} 27 | \item{check.names}{See \code{\link{read.table}}.} 28 | \item{retclass}{character that specifies the class of the returned result. 29 | It can be \code{"zoo"} (the default), \code{"list"} or \code{NULL}. For 30 | details see below.} 31 | \item{drop}{logical. If a \code{"zoo"} object without observations is 32 | merged with a one-dimensional \code{"zoo"} object (vector or 1-column 33 | matrix), should the result be a vector (\code{drop = TRUE}) or a 34 | 1-column matrix (\code{drop = FALSE})? The former is the default 35 | in the \code{Merge} method, the latter in the \code{cbind} method.} 36 | \item{sep}{character. Separator character that should be used when 37 | pasting \code{suffixes} to column names for making them unique.} 38 | } 39 | 40 | \details{ 41 | The \code{merge} method for \code{"zoo"} objects combines the columns 42 | of several objects along the union of the dates 43 | for \code{all = TRUE}, the default, 44 | or the intersection of their dates for \code{all = FALSE} 45 | filling up the created gaps (if any) with the \code{fill} pattern. 46 | 47 | The first argument must be a \code{zoo} object. If any of the remaining 48 | arguments are plain vectors or matrices with the same length or number 49 | of rows as the first argument then such arguments are coerced to \code{"zoo"} 50 | using \code{as.zoo}. If they are plain but have length 1 then they are 51 | merged after all non-scalars such that their column is filled with the 52 | value of the scalar. 53 | 54 | \code{all} can be a vector of the same length as the number of \code{"zoo"} 55 | objects to merged (if not, it is expanded): All indexes 56 | (times) of the objects corresponding to \code{TRUE} are included, for those 57 | corresponding to \code{FALSE} only the indexes present in all objects are 58 | included. This allows intersection, union and left and right joins 59 | to be expressed. 60 | 61 | If \code{retclass} is \code{"zoo"} (the default) a single merged \code{"zoo"} 62 | object is returned. If it is set to \code{"list"} a list of \code{"zoo"} 63 | objects is returned. If \code{retclass = NULL} then instead of returning a value it updates each 64 | argument (if it is a variable rather than an expression) in 65 | place so as to extend or reduce it to use the common index vector. 66 | 67 | The indexes of different 68 | \code{"zoo"} objects can be of different classes and are coerced to 69 | one class in the resulting object (with a warning). 70 | 71 | The default \code{cbind} method is essentially the default \code{merge} 72 | method, but does not support the \code{retclass} argument. 73 | The \code{rbind} 74 | method combines the dates of the \code{"zoo"} objects (duplicate dates are 75 | not allowed) and combines the rows of the objects. Furthermore, the 76 | \code{c} method is identical to the \code{rbind} method. 77 | } 78 | 79 | \value{ 80 | An object of class \code{"zoo"} if \code{retclass="zoo"}, an object of 81 | class \code{"list"} if \code{retclass="list"} or modified arguments as 82 | explained above if \code{retclass=NULL}. If the result is an object 83 | of class \code{"zoo"} then its frequency is the common frequency of its 84 | zoo arguments, if they have a common frequency. 85 | } 86 | 87 | \seealso{\code{\link{zoo}}} 88 | 89 | \examples{ 90 | ## simple merging 91 | x.date <- as.Date(paste(2003, 02, c(1, 3, 7, 9, 14), sep = "-")) 92 | x <- zoo(rnorm(5), x.date) 93 | 94 | y1 <- zoo(matrix(1:10, ncol = 2), 1:5) 95 | y2 <- zoo(matrix(rnorm(10), ncol = 2), 3:7) 96 | 97 | ## using arguments `fill' and `suffixes' 98 | merge(y1, y2, all = FALSE) 99 | merge(y1, y2, all = FALSE, suffixes = c("a", "b")) 100 | merge(y1, y2, all = TRUE) 101 | merge(y1, y2, all = TRUE, fill = 0) 102 | 103 | ## if different index classes are merged, as in 104 | ## the next merge example then ## a warning is issued and 105 | ### the indexes are coerced. 106 | ## It is up to the user to ensure that the result makes sense. 107 | merge(x, y1, y2, all = TRUE) 108 | 109 | ## extend an irregular series to a regular one: 110 | # create a constant series 111 | z <- zoo(1, seq(4)[-2]) 112 | # create a 0 dimensional zoo series 113 | z0 <- zoo(, 1:4) 114 | # do the extension 115 | merge(z, z0) 116 | # same but with zero fill 117 | merge(z, z0, fill = 0) 118 | 119 | merge(z, coredata(z), 1) 120 | 121 | 122 | ## merge multiple series represented in a long form data frame 123 | ## into a multivariate zoo series and plot, one series for each site. 124 | ## Additional examples can be found here: 125 | ## https://stat.ethz.ch/pipermail/r-help/2009-February/187094.html 126 | ## https://stat.ethz.ch/pipermail/r-help/2009-February/187096.html 127 | ## 128 | m <- 5 # no of years 129 | n <- 6 # no of sites 130 | sites <- LETTERS[1:n] 131 | suppressWarnings(RNGversion("3.5.0")) 132 | set.seed(1) 133 | DF <- data.frame(site = sites, year = 2000 + 1:m, data = rnorm(m*n)) 134 | tozoo <- function(x) zoo(x$data, x$year) 135 | Data <- do.call(merge, lapply(split(DF, DF$site), tozoo)) 136 | plot(Data, screen = 1, col = 1:n, pch = 1:n, type = "o", xlab = "") 137 | legend("bottomleft", legend = sites, lty = 1, pch = 1:n, col = 1:n) 138 | 139 | ## for each index value in x merge it with the closest index value in y 140 | ## but retaining x's times. 141 | x<-zoo(1:3,as.Date(c("1992-12-13", "1997-05-12", "1997-07-13"))) 142 | y<-zoo(1:5,as.Date(c("1992-12-15", "1992-12-16", "1997-05-10","1997-05-19", "1997-07-13"))) 143 | f <- function(u) which.min(abs(as.numeric(index(y)) - as.numeric(u))) 144 | ix <- sapply(index(x), f) 145 | cbind(x, y = coredata(y)[ix]) 146 | 147 | ## this merges each element of x with the closest time point in y at or 148 | ## after x's time point (whereas in previous example it could be before 149 | ## or after) 150 | window(na.locf(merge(x, y), fromLast = TRUE), index(x)) 151 | 152 | 153 | ## c() can combine several zoo series, e.g., zoo series with Date index 154 | z <- zoo(1:5, as.Date("2000-01-01") + 0:4) 155 | z2 <- zoo(6:7, time(z)[length(z)] + 1:2) 156 | 157 | ## c() combines these in a single series 158 | c(z, z2) 159 | 160 | ## the order does not matter 161 | c(z2, z) 162 | 163 | ## note, however, that combining a zoo series with an unclassed vector 164 | ## of observations would try to coerce the indexes first 165 | ## which might either give an unexpected result or an error in R >= 4.1.0 166 | ## c(z, 6:7) 167 | 168 | } 169 | \keyword{ts} 170 | -------------------------------------------------------------------------------- /man/na.StructTS.Rd: -------------------------------------------------------------------------------- 1 | \name{na.StructTS} 2 | \alias{na.StructTS} 3 | \alias{na.StructTS.zoo} 4 | \alias{na.StructTS.ts} 5 | \title{Fill NA or specified positions.} 6 | \description{ 7 | Generic function for filling \code{NA} values using seasonal Kalman filter.} 8 | \usage{ 9 | na.StructTS(object, \dots) 10 | \method{na.StructTS}{ts}(object, ..., na.rm = FALSE, maxgap = Inf) 11 | \method{na.StructTS}{zoo}(object, ..., na.rm = FALSE, maxgap = Inf) 12 | } 13 | \arguments{ 14 | \item{object}{an object.} 15 | \item{\dots}{other arguments passed to methods.} 16 | \item{na.rm}{logical. Whether to remove end portions or fill them with NA.} 17 | \item{maxgap}{Runs of more than \code{maxgap} \code{NA}s are retained, 18 | other \code{NA}s are removed and the last occurrence in the resulting series 19 | prior to each time point in \code{xout} is used as that time point's 20 | output value.} 21 | } 22 | 23 | \details{ 24 | Interpolate with seasonal Kalman filter, using \code{\link[stats]{StructTS}}, 25 | followed by \code{\link[stats]{tsSmooth}}. The input object should 26 | be a regular time series and have a frequency. It is assumed the cycle length is 1.} 27 | 28 | \seealso{\code{\link[stats]{StructTS}}, \code{\link[stats]{tsSmooth}}, \code{\link{na.approx}}} 29 | 30 | \examples{ 31 | 32 | z <- zooreg(rep(10 * seq(8), each = 4) + rep(c(3, 1, 2, 4), times = 8), 33 | start = as.yearqtr(2000), freq = 4) 34 | z[25] <- NA 35 | 36 | zout <- na.StructTS(z) 37 | 38 | plot(cbind(z, zout), screen = 1, col = 1:2, type = c("l", "p"), pch = 20) 39 | 40 | 41 | } 42 | \keyword{ts} 43 | -------------------------------------------------------------------------------- /man/na.aggregate.Rd: -------------------------------------------------------------------------------- 1 | \name{na.aggregate} 2 | \alias{na.aggregate} 3 | \alias{na.aggregate.default} 4 | \title{Replace NA by Aggregation} 5 | \description{ 6 | Generic function for replacing each \code{NA} with aggregated 7 | values. This allows imputing by the overall mean, by monthly means, 8 | etc. 9 | } 10 | \usage{ 11 | na.aggregate(object, \dots) 12 | \method{na.aggregate}{default}(object, by = 1, \dots, FUN = mean, 13 | na.rm = FALSE, maxgap = Inf) 14 | 15 | } 16 | \arguments{ 17 | \item{object}{an object.} 18 | \item{by}{a grouping variable corresponding to \code{object}, or a 19 | function to be applied to \code{time(object)} to generate the 20 | groups.} 21 | \item{\dots}{further arguments passed to \code{by} if \code{by} is a 22 | function.} 23 | \item{FUN}{function to apply to the non-missing values in each group 24 | defined by \code{by}.} 25 | \item{na.rm}{logical. Should any remaining \code{NA}s be removed?} 26 | \item{maxgap}{maximum number of consecutive \code{NA}s to 27 | fill. Any longer gaps will be left unchanged.} 28 | } 29 | 30 | \value{ 31 | An object in which each \code{NA} in the input object is replaced 32 | by the mean (or other function) of its group, defined by 33 | \code{by}. This is done for each series in a multi-column object. Common 34 | choices for the aggregation group are a year, a month, all calendar 35 | months, etc. 36 | 37 | If a group has no non-missing values, the default aggregation function 38 | \code{mean} will return \code{NaN}. Specify \code{na.rm = TRUE} to 39 | omit such remaining missing values. 40 | } 41 | 42 | \seealso{\code{\link{zoo}}} 43 | 44 | \examples{ 45 | z <- zoo(c(1, NA, 3:9), 46 | c(as.Date("2010-01-01") + 0:2, 47 | as.Date("2010-02-01") + 0:2, 48 | as.Date("2011-01-01") + 0:2)) 49 | ## overall mean 50 | na.aggregate(z) 51 | ## group by months 52 | na.aggregate(z, as.yearmon) 53 | ## group by calendar months 54 | na.aggregate(z, months) 55 | ## group by years 56 | na.aggregate(z, format, "\%Y") 57 | } 58 | \keyword{ts} 59 | -------------------------------------------------------------------------------- /man/na.approx.Rd: -------------------------------------------------------------------------------- 1 | \name{na.approx} 2 | \alias{na.approx} 3 | \alias{na.approx.zoo} 4 | \alias{na.approx.zooreg} 5 | \alias{na.approx.ts} 6 | \alias{na.approx.default} 7 | \alias{na.spline} 8 | \alias{na.spline.zoo} 9 | \alias{na.spline.zooreg} 10 | \alias{na.spline.ts} 11 | \alias{na.spline.default} 12 | \title{Replace NA by Interpolation} 13 | \description{ 14 | Generic functions for replacing each \code{NA} with interpolated 15 | values. 16 | } 17 | \usage{ 18 | na.approx(object, \dots) 19 | \method{na.approx}{zoo}(object, x = index(object), xout, \dots, na.rm = TRUE, maxgap = Inf, along) 20 | \method{na.approx}{zooreg}(object, \dots) 21 | \method{na.approx}{ts}(object, \dots) 22 | \method{na.approx}{default}(object, x = index(object), xout, \dots, na.rm = TRUE, maxgap = Inf, along) 23 | 24 | na.spline(object, \dots) 25 | \method{na.spline}{zoo}(object, x = index(object), xout, \dots, na.rm = TRUE, maxgap = Inf, along) 26 | \method{na.spline}{zooreg}(object, \dots) 27 | \method{na.spline}{ts}(object, \dots) 28 | \method{na.spline}{default}(object, x = index(object), xout, \dots, na.rm = TRUE, maxgap = Inf, along) 29 | 30 | } 31 | \arguments{ 32 | \item{object}{object in which \code{NA}s are to be replaced} 33 | \item{x, xout}{Variables to be used for interpolation as in \code{\link{approx}}.} 34 | \item{na.rm}{logical. If the result of the (spline) interpolation 35 | still results in leading and/or trailing \code{NA}s, should these be removed 36 | (using \code{\link{na.trim}})?} 37 | \item{maxgap}{maximum number of consecutive \code{NA}s to 38 | fill. Any longer gaps will be left unchanged. Note that all methods listed 39 | above can accept \code{maxgap} as it is ultimately passed to the 40 | \code{default} method. In \code{na.spline} the \code{maxgap} argument cannot 41 | be combined with \code{xout}, though.} 42 | \item{along}{deprecated.} 43 | \item{\dots}{further arguments passed to methods. The \code{n} argument of \code{\link{approx}} is currently not supported.} 44 | } 45 | 46 | \details{ 47 | Missing values (\code{NA}s) are replaced by linear interpolation via 48 | \code{\link{approx}} or cubic spline interpolation via \code{\link{spline}}, 49 | respectively. 50 | 51 | It can also be used for series disaggregation by specifying \code{xout}. 52 | 53 | By default the index associated with \code{object} is used 54 | for interpolation. Note, that if this calls \code{index.default} 55 | this gives an equidistant spacing \code{1:NROW(object)}. If \code{object} 56 | is a matrix or data.frame, the interpolation is done separately for 57 | each column. 58 | 59 | If \code{obj} is a plain vector then \code{na.approx(obj, x, y, xout, ...)} 60 | returns \code{approx(x = x[!na], y = coredata(obj)[!na], xout = xout, ...)} 61 | (where \code{na} indicates observations with \code{NA}) such that \code{xout} 62 | defaults to \code{x}. Note that if there are less than two non-\code{NA}s then 63 | \code{approx()} cannot be applied and thus no \code{NA}s can be replaced. 64 | 65 | If \code{obj} is a \code{zoo}, \code{zooreg} or \code{ts} object its 66 | \code{coredata} value is processed as described and its time index is \code{xout} if 67 | specified and \code{index(obj)} otherwise. If \code{obj} is two dimensional 68 | then the above is applied to each column separately. For examples, see below. 69 | 70 | If \code{obj} has more than one column, the above strategy is applied to 71 | each column. 72 | } 73 | 74 | \value{ 75 | An object of similar structure as \code{object} with \code{NA}s replaced by 76 | interpolation. For \code{na.approx} only the internal \code{NA}s are replaced and 77 | leading or trailing \code{NA}s are omitted if \code{na.rm = TRUE} or not 78 | replaced if \code{na.rm = FALSE}. 79 | } 80 | 81 | \seealso{\code{\link{zoo}}, \code{\link{approx}}, \code{\link{na.contiguous}}, 82 | \code{\link{na.locf}}, \code{\link{na.omit}}, \code{\link{na.trim}}, \code{\link{spline}}, 83 | \code{\link[stinepack]{stinterp}} 84 | } 85 | 86 | \examples{ 87 | 88 | z <- zoo(c(2, NA, 1, 4, 5, 2), c(1, 3, 4, 6, 7, 8)) 89 | 90 | ## use underlying time scale for interpolation 91 | na.approx(z) 92 | ## use equidistant spacing 93 | na.approx(z, 1:6) 94 | 95 | # with and without na.rm = FALSE 96 | zz <- c(NA, 9, 3, NA, 3, 2) 97 | na.approx(zz, na.rm = FALSE) 98 | na.approx(zz) 99 | 100 | d0 <- as.Date("2000-01-01") 101 | z <- zoo(c(11, NA, 13, NA, 15, NA), d0 + 1:6) 102 | 103 | # NA fill, drop or keep leading/trailing NAs 104 | na.approx(z) 105 | na.approx(z, na.rm = FALSE) 106 | 107 | # extrapolate to point outside of range of time points 108 | # (a) drop NA, (b) keep NA, (c) extrapolate using rule = 2 from approx() 109 | na.approx(z, xout = d0 + 7) 110 | na.approx(z, xout = d0 + 7, na.rm = FALSE) 111 | na.approx(z, xout = d0 + 7, rule = 2) 112 | 113 | # use splines - extrapolation handled differently 114 | z <- zoo(c(11, NA, 13, NA, 15, NA), d0 + 1:6) 115 | na.spline(z) 116 | na.spline(z, na.rm = FALSE) 117 | na.spline(z, xout = d0 + 1:6) 118 | na.spline(z, xout = d0 + 2:5) 119 | na.spline(z, xout = d0 + 7) 120 | na.spline(z, xout = d0 + 7, na.rm = FALSE) 121 | 122 | ## using na.approx for disaggregation 123 | zy <- zoo(1:3, 2000:2001) 124 | 125 | # yearly to monthly series 126 | zmo <- na.approx(zy, xout = as.yearmon(2000+0:13/12)) 127 | zmo 128 | 129 | # monthly to daily series 130 | sq <- seq(as.Date(start(zmo)), as.Date(end(zmo), frac = 1), by = "day") 131 | zd <- na.approx(zmo, x = as.Date, xout = sq) 132 | head(zd) 133 | 134 | # weekly to daily series 135 | zww <- zoo(1:3, as.Date("2001-01-01") + seq(0, length = 3, by = 7)) 136 | zww 137 | zdd <- na.approx(zww, xout = seq(start(zww), end(zww), by = "day")) 138 | zdd 139 | 140 | # The lines do not show up because of the NAs 141 | plot(cbind(z, z), type = "b", screen = 1) 142 | # use na.approx to force lines to appear 143 | plot(cbind(z, na.approx(z)), type = "b", screen = 1) 144 | 145 | # Workaround where less than 2 NAs can appear in a column 146 | za <- zoo(cbind(1:5, NA, c(1:3, NA, 5), NA)); za 147 | 148 | ix <- colSums(!is.na(za)) > 0 149 | za[, ix] <- na.approx(za[, ix]); za 150 | 151 | # using na.approx to create regularly spaced series 152 | # z has points at 10, 20 and 40 minutes while output also has a point at 30 153 | if(require("chron")) { 154 | tt <- as.chron("2000-01-01 10:00:00") + c(1, 2, 4) * as.numeric(times("00:10:00")) 155 | z <- zoo(1:3, tt) 156 | tseq <- seq(start(z), end(z), by = times("00:10:00")) 157 | na.approx(z, xout = tseq) 158 | } 159 | } 160 | 161 | \keyword{ts} 162 | -------------------------------------------------------------------------------- /man/na.fill.Rd: -------------------------------------------------------------------------------- 1 | \name{na.fill} 2 | \alias{na.fill} 3 | \alias{na.fill0} 4 | \alias{na.fill.ts} 5 | \alias{na.fill.zoo} 6 | \alias{na.fill.default} 7 | \title{Fill NA or specified positions.} 8 | \description{ 9 | Generic function for filling \code{NA} values or specified positions. 10 | } 11 | \usage{ 12 | na.fill(object, fill, \dots) 13 | \method{na.fill}{ts}(object, fill, ix, \dots) 14 | \method{na.fill}{zoo}(object, fill, ix, \dots) 15 | \method{na.fill}{default}(object, fill, ix, \dots) 16 | 17 | na.fill0(object, fill, ix = !is.na(object)) 18 | } 19 | \arguments{ 20 | \item{object}{an object.} 21 | \item{fill}{a three component list or a vector that is coerced to a 22 | list. Shorter objects are recycled. The three components 23 | represent the fill value to the left of the data, within the 24 | interior of the data and to the right of the data, 25 | respectively. The value of any component may be the keyword 26 | \code{"extend"} to indicate repetition of the 27 | leftmost or rightmost non-NA value or linear interpolation in the interior. 28 | \code{NULL} means that items are dropped rather than filled.} 29 | \item{ix}{logical. Should be the same length as the number of time points. 30 | Indicates which time points not to fill. This defaults to the non-NA values.} 31 | \item{\dots}{further arguments passed to methods.} 32 | } 33 | 34 | \details{ 35 | \code{na.fill} is a generic function for filling \code{NA} or indicated values. 36 | It currently has methods for the time series classes \code{"zoo"} and \code{"ts"} 37 | and a default method based on the \code{"zoo"} method. 38 | 39 | Furthermore, \code{na.fill0} works with plain vectors and \code{"Date"} objects. 40 | It also works with \code{"zoo"} objects provided that no \code{fill} component is \code{NULL}. 41 | } 42 | 43 | \seealso{\code{\link{na.approx}}} 44 | 45 | \examples{ 46 | 47 | z <- zoo(c(NA, 2, NA, 1, 4, 5, 2, NA)) 48 | na.fill(z, "extend") 49 | na.fill(z, c("extend", NA)) 50 | na.fill(z, -(1:3)) 51 | na.fill(z, list(NA, NULL, NA)) 52 | 53 | } 54 | \keyword{ts} 55 | -------------------------------------------------------------------------------- /man/na.locf.Rd: -------------------------------------------------------------------------------- 1 | \name{na.locf} 2 | \alias{na.locf} 3 | \alias{na.locf0} 4 | \alias{na.locf.data.frame} 5 | \alias{na.locf.list} 6 | \alias{na.locf.default} 7 | \title{Last Observation Carried Forward} 8 | \description{ 9 | Generic function for replacing each \code{NA} with the most recent 10 | non-\code{NA} prior to it. 11 | } 12 | \usage{ 13 | na.locf(object, na.rm = TRUE, \dots) 14 | \method{na.locf}{default}(object, na.rm = TRUE, fromLast, rev, 15 | maxgap = Inf, rule = 2, \dots) 16 | 17 | na.locf0(object, fromLast = FALSE, maxgap = Inf, coredata = NULL) 18 | } 19 | \arguments{ 20 | \item{object}{an object.} 21 | \item{na.rm}{logical. Should leading \code{NA}s be removed?} 22 | \item{fromLast}{logical. Causes observations to be carried backward rather 23 | than forward. Default is \code{FALSE}. With a value of \code{TRUE} 24 | this corresponds to NOCB (next observation carried backward). 25 | It is not supported if \code{x} or \code{xout} is specified.} 26 | \item{rev}{Use \code{fromLast} instead. This argument will 27 | be eliminated in the future in favor of \code{fromLast}.} 28 | \item{maxgap}{Runs of more than \code{maxgap} \code{NA}s are retained, 29 | other \code{NA}s are removed and the last occurrence in the resulting series 30 | prior to each time point in \code{xout} is used as that time point's output value. 31 | (If \code{xout} is not specified this reduces to retaining runs of more than 32 | \code{maxgap} \code{NA}s while filling other \code{NA}s with the last 33 | occurrence of a non-\code{NA}.)} 34 | \item{rule}{See \code{\link{approx}}.} 35 | \item{\dots}{further arguments passed to methods.} 36 | \item{coredata}{logical. Should LOCF be applied to the core data 37 | of a (time series) object and then assigned to the original object 38 | again? By default, this strategy is applied to time series classes 39 | (e.g., \code{ts}, \code{zoo}, \code{xts}, etc.) where it preserves 40 | the time index.} 41 | } 42 | 43 | \value{ 44 | An object in which each \code{NA} in the input object is replaced 45 | by the most recent non-\code{NA} prior to it. If there are no earlier non-\code{NA}s then 46 | the \code{NA} is omitted (if \code{na.rm = TRUE}) or it is not replaced (if \code{na.rm = FALSE}). 47 | 48 | The arguments \code{x} and \code{xout} can be used in which case they have 49 | the same meaning as in \code{\link{approx}}. 50 | 51 | Note that if a multi-column zoo object has a column entirely composed of 52 | \code{NA} then with \code{na.rm = TRUE}, the default, 53 | the above implies that the resulting object will have 54 | zero rows. Use \code{na.rm = FALSE} to preserve the \code{NA} values instead. 55 | 56 | The function \code{na.locf0} is the workhorse function underlying the default 57 | \code{na.locf} method. It has more limited capabilities but is faster for the 58 | special cases it covers. Implicitly, it uses \code{na.rm=FALSE}. 59 | } 60 | 61 | \seealso{\code{\link{zoo}}} 62 | 63 | \examples{ 64 | az <- zoo(1:6) 65 | 66 | bz <- zoo(c(2,NA,1,4,5,2)) 67 | na.locf(bz) 68 | na.locf(bz, fromLast = TRUE) 69 | 70 | cz <- zoo(c(NA,9,3,2,3,2)) 71 | na.locf(cz) 72 | 73 | # generate and fill in missing dates 74 | z <- zoo(c(0.007306621, 0.007659046, 0.007681013, 75 | 0.007817548, 0.007847579, 0.007867313), 76 | as.Date(c("1993-01-01", "1993-01-09", "1993-01-16", 77 | "1993-01-23", "1993-01-30", "1993-02-06"))) 78 | g <- seq(start(z), end(z), "day") 79 | na.locf(z, xout = g) 80 | 81 | # similar but use a 2 second grid 82 | 83 | z <- zoo(1:9, as.POSIXct(c("2010-01-04 09:30:02", "2010-01-04 09:30:06", 84 | "2010-01-04 09:30:07", "2010-01-04 09:30:08", "2010-01-04 09:30:09", 85 | "2010-01-04 09:30:10", "2010-01-04 09:30:11", "2010-01-04 09:30:13", 86 | "2010-01-04 09:30:14"))) 87 | 88 | g <- seq(start(z), end(z), by = "2 sec") 89 | na.locf(z, xout = g) 90 | 91 | ## get 5th of every month or most recent date prior to 5th if 5th missing. 92 | ## Result has index of the date actually used. 93 | 94 | z <- zoo(c(1311.56, 1309.04, 1295.5, 1296.6, 1286.57, 1288.12, 95 | 1289.12, 1289.12, 1285.33, 1307.65, 1309.93, 1311.46, 1311.28, 96 | 1308.11, 1301.74, 1305.41, 1309.72, 1310.61, 1305.19, 1313.21, 97 | 1307.85, 1312.25, 1325.76), as.Date(c(13242, 13244, 98 | 13245, 13248, 13249, 13250, 13251, 13252, 13255, 13256, 13257, 99 | 13258, 13259, 13262, 13263, 13264, 13265, 13266, 13269, 13270, 100 | 13271, 13272, 13274))) 101 | 102 | # z.na is same as z but with missing days added (with NAs) 103 | # It is formed by merging z with a zero with series having all the dates. 104 | 105 | rng <- range(time(z)) 106 | z.na <- merge(z, zoo(, seq(rng[1], rng[2], by = "day"))) 107 | 108 | # use na.locf to bring values forward picking off 5th of month 109 | na.locf(z.na)[as.POSIXlt(time(z.na))$mday == 5] 110 | 111 | ## this is the same as the last one except instead of always using the 112 | ## 5th of month in the result we show the date actually used 113 | 114 | # idx has NAs wherever z.na does but has 1, 2, 3, ... instead of 115 | # z.na's data values (so idx can be used for indexing) 116 | 117 | idx <- coredata(na.locf(seq_along(z.na) + (0 * z.na))) 118 | 119 | # pick off those elements of z.na that correspond to 5th 120 | 121 | z.na[idx[as.POSIXlt(time(z.na))$mday == 5]] 122 | 123 | ## only fill single-day gaps 124 | 125 | merge(z.na, filled1 = na.locf(z.na, maxgap = 1)) 126 | 127 | ## fill NAs in first column by inflating the most recent non-NA 128 | ## by the growth in second column. Note that elements of x-x 129 | ## are NA if the corresponding element of x is NA and zero else 130 | 131 | m <- zoo(cbind(c(1, 2, NA, NA, 5, NA, NA), seq(7)^2), as.Date(1:7)) 132 | 133 | r <- na.locf(m[,1]) * m[,2] / na.locf(m[,2] + (m[,1]-m[,1])) 134 | cbind(V1 = r, V2 = m[,2]) 135 | 136 | ## repeat a quarterly value every month 137 | ## preserving NAs 138 | zq <- zoo(c(1, NA, 3, 4), as.yearqtr(2000) + 0:3/4) 139 | tt <- as.yearmon(start(zq)) + seq(0, len = 3 * length(zq))/12 140 | na.locf(zq, xout = tt, maxgap = 0) 141 | 142 | ## na.locf() can also be mimicked with ave() 143 | x <- c(NA, 10, NA, NA, 20, NA) 144 | f <- function(x) x[1] 145 | ave(x, cumsum(!is.na(x)), FUN = f) 146 | 147 | ## by replacing f() with other functions various generalizations can be 148 | ## obtained, e.g., 149 | f <- function(x) if (length(x) > 3) x else x[1] # like maxgap 150 | f <- function(x) replace(x, 1:min(length(x)), 3) # replace up to 2 NAs 151 | f <- function(x) if (!is.na(x[1]) && x[1] > 0) x[1] else x # only positve numbers 152 | } 153 | \keyword{ts} 154 | -------------------------------------------------------------------------------- /man/na.trim.Rd: -------------------------------------------------------------------------------- 1 | \name{na.trim} 2 | \alias{na.trim} 3 | \alias{na.trim.default} 4 | \alias{na.trim.ts} 5 | \title{Trim Leading/Trailing Missing Observations} 6 | \description{ 7 | Generic function for removing leading and trailing \code{NA}s. 8 | } 9 | \usage{ 10 | na.trim(object, \dots) 11 | \method{na.trim}{default}(object, sides = c("both", "left", "right"), 12 | is.na = c("any", "all"), maxgap = Inf, \dots) 13 | } 14 | \arguments{ 15 | \item{object}{an object.} 16 | \item{sides}{character specifying whether \code{NA}s are to be removed from 17 | both sides, just from the left side or just from the right side.} 18 | \item{is.na}{If "any" then a row will be regarded as \code{NA} if it has 19 | any \code{NA}s. If "all" then a row will be regarded as \code{NA} 20 | only if all elements in the row are \code{NA}. For one dimensional 21 | zoo objects this argument has no effect.} 22 | \item{maxgap}{maximum number of consecutive \code{NA}s to 23 | trim. Any longer gaps will be left unchanged.} 24 | \item{\dots}{further arguments passed to methods.} 25 | } 26 | 27 | \value{ 28 | An object in which leading and/or trailing 29 | \code{NA}s have been removed. 30 | } 31 | 32 | \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}}} 33 | \examples{ 34 | # examples of na.trim 35 | x <- zoo(c(1, 4, 6), c(2, 4, 6)) 36 | xx <- zoo(matrix(c(1, 4, 6, NA, 5, 7), 3), c(2, 4, 6)) 37 | na.trim(x) 38 | na.trim(xx) 39 | 40 | # using na.trim for alignment 41 | # cal defines the legal dates 42 | # all dates within the date range of x should be present 43 | cal <- zoo(,c(1, 2, 3, 6, 7)) 44 | x <- zoo(c(12, 16), c(2, 6)) 45 | na.trim(merge(x, cal)) 46 | 47 | } 48 | \keyword{ts} 49 | -------------------------------------------------------------------------------- /man/rollmean.Rd: -------------------------------------------------------------------------------- 1 | \name{rollmean} 2 | 3 | \alias{rollmean} 4 | \alias{rollmax} 5 | \alias{rollmedian} 6 | \alias{rollsum} 7 | 8 | \alias{rollmeanr} 9 | \alias{rollmaxr} 10 | \alias{rollmedianr} 11 | \alias{rollsumr} 12 | 13 | \alias{rollmean.zoo} 14 | \alias{rollmax.zoo} 15 | \alias{rollmedian.zoo} 16 | \alias{rollsum.zoo} 17 | 18 | \alias{rollmean.ts} 19 | \alias{rollmax.ts} 20 | \alias{rollmedian.ts} 21 | \alias{rollsum.ts} 22 | 23 | \alias{rollmean.default} 24 | \alias{rollmax.default} 25 | \alias{rollmedian.default} 26 | \alias{rollsum.default} 27 | 28 | \title{Rolling Means/Maximums/Medians/Sums} 29 | 30 | \description{ 31 | Generic functions for computing rolling means, maximums, medians, and sums of ordered observations. 32 | } 33 | 34 | \usage{ 35 | rollmean(x, k, fill = if (na.pad) NA, na.pad = FALSE, 36 | align = c("center", "left", "right"), ...) 37 | 38 | rollmax(x, k, fill = if (na.pad) NA, na.pad = FALSE, 39 | align = c("center", "left", "right"), ...) 40 | 41 | rollmedian(x, k, fill = if (na.pad) NA, na.pad = FALSE, 42 | align = c("center", "left", "right"), ...) 43 | 44 | rollsum(x, k, fill = if (na.pad) NA, na.pad = FALSE, 45 | align = c("center", "left", "right"), ...) 46 | 47 | rollmeanr(..., align = "right") 48 | rollmaxr(..., align = "right") 49 | rollmedianr(..., align = "right") 50 | rollsumr(..., align = "right") 51 | } 52 | 53 | \arguments{ 54 | \item{x}{an object (representing a series of observations).} 55 | \item{k}{integer width of the rolling window. Must be odd for \code{rollmedian}.} 56 | \item{fill}{a three-component vector or list (recycled otherwise) providing 57 | filling values at the left/within/to the right of the data range. 58 | See the \code{fill} argument of \code{\link{na.fill}} for details.} 59 | \item{na.pad}{deprecated. Use \code{fill = NA} instead of \code{na.pad = TRUE}.} 60 | \item{align}{character specifying whether the index of the result 61 | should be left- or right-aligned or centered (default) compared 62 | to the rolling window of observations.} 63 | \item{\dots}{Further arguments passed to methods.} 64 | } 65 | 66 | \details{ 67 | These functions compute rolling means, maximums, medians, and sums respectively 68 | and are thus similar to \code{\link{rollapply}} but are 69 | optimized for speed. 70 | 71 | Currently, there are methods for \code{"zoo"} and \code{"ts"} series and 72 | default methods. The default method of \code{rollmedian} 73 | is an interface to \code{\link{runmed}}. 74 | The default methods of \code{rollmean} and \code{rollsum} do not handle inputs that contain 75 | \code{NA}s. In such cases, use \code{\link{rollapply}} instead. 76 | 77 | If \code{x} is of length 0, \code{x} is returned unmodified. 78 | } 79 | 80 | \value{ 81 | An object of the same class as \code{x} with the rolling mean/max/median/sum. 82 | } 83 | 84 | \seealso{\code{\link{rollapply}}, \code{\link{zoo}}, \code{\link{na.fill}}} 85 | 86 | \examples{ 87 | suppressWarnings(RNGversion("3.5.0")) 88 | set.seed(1) 89 | 90 | x.Date <- as.Date(paste(2004, rep(1:4, 4:1), sample(1:28, 10), sep = "-")) 91 | x <- zoo(rnorm(12), x.Date) 92 | 93 | ## rolling operations for univariate series 94 | rollmean(x, 3) 95 | rollmax(x, 3) 96 | rollmedian(x, 3) 97 | rollsum(x, 3) 98 | 99 | ## rolling operations for multivariate series 100 | xm <- zoo(matrix(1:12, 4, 3), x.Date[1:4]) 101 | rollmean(xm, 3) 102 | rollmax(xm, 3) 103 | rollmedian(xm, 3) 104 | rollsum(xm, 3) 105 | 106 | ## rollapply vs. dedicated rollmean 107 | rollapply(xm, 3, mean) # uses rollmean 108 | rollapply(xm, 3, function(x) mean(x)) # does not use rollmean 109 | } 110 | \keyword{ts} 111 | -------------------------------------------------------------------------------- /man/tinyplot.zoo.Rd: -------------------------------------------------------------------------------- 1 | \name{tinyplot.zoo} 2 | \alias{tinyplot.zoo} 3 | 4 | \title{Plotting zoo Objects with tinyplot} 5 | 6 | \details{ 7 | Convenience interface for visualizing zoo objects with tinyplot. 8 | } 9 | 10 | \usage{ 11 | \method{tinyplot}{zoo}(object, facet, type = "l", 12 | facet.args = list(free = TRUE), ylab = "", \dots) 13 | } 14 | 15 | \arguments{ 16 | \item{object}{an object of class \code{"zoo"}.} 17 | \item{facet}{specification of \code{facet} for \code{\link[tinyplot]{tinyplot.formula}}. The 18 | default in the \code{tinyplot} method is to use \code{facet = NULL} for univariate 19 | series and \code{facet = ~ Series} for multivariate series.} 20 | \item{type, facet.args, ylab, \dots}{further arguments passed to \code{tinyplot}.} 21 | } 22 | 23 | \description{ 24 | The approach is similar to that in \code{\link{autoplot.zoo}} 25 | (based on ggplot2) and uses \code{\link{fortify.zoo}} (with \code{melt = TRUE}) 26 | to convert the zoo object into a data frame and then uses a suitable 27 | formula to visiualize the series. 28 | } 29 | 30 | \seealso{ 31 | \code{\link[tinyplot]{tinyplot}}, \code{\link{autoplot.zoo}} 32 | } 33 | 34 | \examples{ 35 | if(require("tinyplot")) { 36 | suppressWarnings(RNGversion("3.5.0")) 37 | set.seed(1) 38 | 39 | ## example data 40 | x.Date <- as.Date(paste(2003, 02, c(1, 3, 7, 9, 14), sep = "-")) 41 | x <- zoo(rnorm(5), x.Date) 42 | xlow <- x - runif(5) 43 | xhigh <- x + runif(5) 44 | z <- cbind(x, xlow, xhigh) 45 | 46 | ## univariate plotting 47 | tinyplot(x) 48 | 49 | ## multivariate plotting in multiple or single panels 50 | tinyplot(z) ## multiple without color/linetype with free scales 51 | tinyplot(z, facet.args = NULL) ## multiple without color/linetype with same scale 52 | tinyplot(z, facet = ~ Series) ## multiple with series-dependent color/linetype 53 | tinyplot(z, facet = NULL) ## single with series-dependent color/linetype 54 | 55 | ## by hand with color/linetype and with/without facets 56 | d <- fortify.zoo(z, melt = TRUE) 57 | tinyplot(Value ~ Index | Series, data = d, type = "l") 58 | tinyplot(Value ~ Index | Series, facet = "by", data = d, type = "l") 59 | tinyplot(Value ~ Index | Series, facet = "by", data = d, type = "l", facet.args = list(free = TRUE)) 60 | 61 | ## EuStockMarkets data (coerced from "ts") 62 | eusm <- as.zoo(EuStockMarkets) 63 | tinyplot(eusm) 64 | tinytheme("clean2") 65 | tinyplot(eusm, facet = NULL) 66 | tinyplot(eusm, facet = ~ Series) 67 | tinyplot(eusm, facet = ~ Series, facet.args = NULL) 68 | tinytheme() ## reset 69 | 70 | } 71 | } 72 | 73 | -------------------------------------------------------------------------------- /man/window.zoo.Rd: -------------------------------------------------------------------------------- 1 | \name{window.zoo} 2 | \alias{window.zoo} 3 | \alias{window<-.zoo} 4 | \title{Extract/Replacing the Time Windows of Objects} 5 | \description{ 6 | Methods for extracting time windows 7 | of \code{"zoo"} objects and replacing it. 8 | } 9 | 10 | \usage{ 11 | \method{window}{zoo}(x, index. = index(x), start = NULL, end = NULL, \dots) 12 | \method{window}{zoo}(x, index. = index(x), start = NULL, end = NULL, \dots) <- value 13 | } 14 | 15 | \arguments{ 16 | \item{x}{an object.} 17 | \item{index.}{the index/time window which should be extracted.} 18 | \item{start}{an index/time value. Only the indexes in \code{index} 19 | which are greater or equal to \code{start} are used. If the index 20 | class supports comparisons to character variables, as does \code{"Date"} 21 | class, \code{"yearmon"} class, \code{"yearqtr"} class and 22 | the \code{chron} package classes \code{"dates"} and \code{"times"} 23 | then \code{start} may alternately be a character variable.} 24 | \item{end}{an index/time value. Only the indexes in \code{index} 25 | which are lower or equal to \code{end} are used. Similar comments 26 | about character variables mentioned under \code{start} apply 27 | here too.} 28 | \item{value}{a suitable value object for use with \code{window(x)}.} 29 | \item{\dots}{currently not used.} 30 | } 31 | 32 | \value{ 33 | Either the time window of the object is extracted (and hence return a \code{"zoo"} 34 | object) or it is replaced. 35 | } 36 | 37 | \seealso{\code{\link{zoo}}} 38 | 39 | \examples{ 40 | suppressWarnings(RNGversion("3.5.0")) 41 | set.seed(1) 42 | 43 | ## zoo example 44 | x.date <- as.Date(paste(2003, rep(1:4, 4:1), seq(1,19,2), sep = "-")) 45 | x <- zoo(matrix(rnorm(20), ncol = 2), x.date) 46 | x 47 | 48 | window(x, start = as.Date("2003-02-01"), end = as.Date("2003-03-01")) 49 | window(x, index = x.date[1:6], start = as.Date("2003-02-01")) 50 | window(x, index = x.date[c(4, 8, 10)]) 51 | window(x, index = x.date[c(4, 8, 10)]) <- matrix(1:6, ncol = 2) 52 | x 53 | 54 | ## for classes that support comparisons with "character" variables 55 | ## start and end may be "character". 56 | window(x, start = "2003-02-01") 57 | 58 | ## zooreg example (with plain numeric index) 59 | z <- zooreg(rnorm(10), start = 2000, freq = 4) 60 | window(z, start = 2001.75) 61 | window(z, start = c(2001, 4)) 62 | 63 | ## replace data at times of d0 which are in dn 64 | d1 <- d0 <- zoo(1:10) + 100 65 | dn <- - head(d0, 4) 66 | window(d1, time(dn)) <- coredata(dn) 67 | 68 | ## if the underlying time index is a float, note that the index may 69 | ## print in the same way but actually be different (e.g., differing 70 | ## by 0.1 second in this example) 71 | zp <- zoo(1:4, as.POSIXct("2000-01-01 00:00:00") + c(-3600, 0, 0.1, 3600)) 72 | ## and then the >= start and <= end may not select all intended 73 | ## observations and adding/subtracting some "fuzz" may be needed 74 | window(zp, end = "2000-01-01 00:00:00") 75 | window(zp, end = as.POSIXct("2000-01-01 00:00:00") + 0.5) 76 | } 77 | \keyword{ts} 78 | -------------------------------------------------------------------------------- /man/xblocks.Rd: -------------------------------------------------------------------------------- 1 | \name{xblocks} 2 | \alias{xblocks} 3 | \alias{xblocks.default} 4 | \alias{xblocks.zoo} 5 | \alias{xblocks.ts} 6 | \title{ 7 | Plot contiguous blocks along x axis. 8 | } 9 | \description{ 10 | Plot contiguous blocks along x axis. A typical use would be to 11 | highlight events or periods of missing data. 12 | } 13 | \usage{ 14 | xblocks(x, ...) 15 | 16 | \S3method{xblocks}{default}(x, y, ..., col = NULL, border = NA, 17 | ybottom = par("usr")[3], ytop = ybottom + height, 18 | height = diff(par("usr")[3:4]), 19 | last.step = median(diff(tail(x)))) 20 | 21 | \S3method{xblocks}{zoo}(x, y = x, ...) 22 | 23 | \S3method{xblocks}{ts}(x, y = x, ...) 24 | } 25 | \arguments{ 26 | \item{x, y}{ 27 | In the default method, \code{x} gives the ordinates along the x axis and 28 | must be in increasing order. \code{y} gives the color values to plot as 29 | contiguous blocks. If \code{y} is numeric, data coverage is plotted, 30 | by converting it into a logical (\code{!is.na(y)}). Finally, if 31 | \code{y} is a function, it is applied to \code{x} (\code{time(x)} in 32 | the time series methods). 33 | 34 | If \code{y} has character (or factor) values, these are interpreted 35 | as colors -- and should therefore be color names or hex 36 | codes. Missing values in \code{y} are not plotted. The default color 37 | is taken from \code{palette()[1]}. If \code{col} is given, this 38 | over-rides the block colors given as \code{y}. 39 | 40 | The \code{ts} and \code{zoo} methods plot the \code{coredata(y)} 41 | values against the time index \code{index(x)}. 42 | } 43 | \item{\dots}{ 44 | In the default method, further arguments are graphical parameters 45 | passed on to \code{\link[grid]{gpar}}. 46 | } 47 | \item{col}{ 48 | if \code{col} is specified, it determines the colors of the blocks 49 | defined by \code{y}. If multiple colors are specified they will be 50 | repeated to cover the total number of blocks. 51 | } 52 | \item{border}{ 53 | border color. 54 | } 55 | \item{ybottom, ytop, height}{ 56 | y axis position of the blocks. The default it to fill the whole plot 57 | region, but by setting these values one can draw blocks along the 58 | top of bottom of the plot. Note that \code{height} is not used 59 | directly, it only sets the default value of \code{ytop}. 60 | } 61 | \item{last.step}{ 62 | width (in native units) of the final block. Defaults to the median of 63 | the last 5 time steps (assuming steps are regular). 64 | } 65 | } 66 | \details{ 67 | Blocks are drawn forward in "time" from the specified x locations, 68 | up until the following value. Contiguous blocks are calculated using 69 | \code{\link{rle}}. 70 | } 71 | \author{ 72 | Felix Andrews \email{felix@nfrac.org} 73 | } 74 | \seealso{ 75 | \code{\link{rect}} 76 | } 77 | \examples{ 78 | ## example time series: 79 | suppressWarnings(RNGversion("3.5.0")) 80 | set.seed(0) 81 | flow <- ts(filter(rlnorm(200, mean = 1), 0.8, method = "r")) 82 | 83 | ## highlight values above and below thresholds. 84 | ## this draws on top using semi-transparent colors. 85 | rgb <- hcl(c(0, 0, 260), c = c(100, 0, 100), l = c(50, 90, 50), alpha = 0.3) 86 | plot(flow) 87 | xblocks(flow > 30, col = rgb[1]) ## high values red 88 | xblocks(flow < 15, col = rgb[3]) ## low value blue 89 | xblocks(flow >= 15 & flow <= 30, col = rgb[2]) ## the rest gray 90 | 91 | ## same thing: 92 | plot(flow) 93 | xblocks(time(flow), cut(flow, c(0,15,30,Inf), labels = rev(rgb))) 94 | 95 | ## another approach is to plot blocks underneath without transparency. 96 | plot(flow) 97 | ## note that 'ifelse' keeps its result as class 'ts' 98 | xblocks(ifelse(flow < mean(flow), hcl(0, 0, 90), hcl(0, 80, 70))) 99 | ## need to redraw data series on top: 100 | lines(flow) 101 | box() 102 | 103 | ## for single series only: plot.default has a panel.first argument 104 | plot(time(flow), flow, type = "l", 105 | panel.first = xblocks(flow > 20, col = "lightgray")) 106 | ## (see also the 'panel' argument for use with multiple series, below) 107 | 108 | ## insert some missing values 109 | flow[c(1:10, 50:80, 100)] <- NA 110 | 111 | ## the default plot shows data coverage 112 | ## (most useful when displaying multiple series, see below) 113 | plot(flow) 114 | xblocks(flow) 115 | 116 | ## can also show gaps: 117 | plot(flow, type = "s") 118 | xblocks(time(flow), is.na(flow), col = "gray") 119 | 120 | ## Example of alternating colors, here showing calendar months 121 | flowdates <- as.Date("2000-01-01") + as.numeric(time(flow)) 122 | flowz <- zoo(coredata(flow), flowdates) 123 | plot(flowz) 124 | xblocks(flowz, months, ## i.e. months(time(flowz)), 125 | col = gray.colors(2, start = 0.7), border = "slategray") 126 | lines(flowz) 127 | 128 | ## Example of multiple series. 129 | ## set up example data 130 | z <- ts(cbind(A = 0:5, B = c(6:7, NA, NA, 10:11), C = c(NA, 13:17))) 131 | 132 | ## show data coverage only (highlighting gaps) 133 | plot(z, panel = function(x, ...) 134 | xblocks(x, col = "darkgray")) 135 | 136 | ## draw gaps in darkgray 137 | plot(z, type = "s", panel = function(x, ...) { 138 | xblocks(time(x), is.na(x), col = "darkgray") 139 | lines(x, ...); points(x) 140 | }) 141 | 142 | ## Example of overlaying blocks from a different series. 143 | ## Are US presidential approval ratings linked to sunspot activity? 144 | ## Set block height to plot blocks along the bottom. 145 | plot(presidents) 146 | xblocks(sunspot.year > 50, height = 2) 147 | } 148 | \keyword{ dplot } 149 | -------------------------------------------------------------------------------- /man/yearmon.Rd: -------------------------------------------------------------------------------- 1 | \name{yearmon} 2 | \alias{yearmon} 3 | \alias{as.yearmon} 4 | \alias{as.yearmon.default} 5 | \alias{as.yearmon.numeric} 6 | \alias{as.yearmon.integer} 7 | \alias{as.yearmon.date} 8 | \alias{as.yearmon.dates} 9 | \alias{as.yearmon.Date} 10 | \alias{as.yearmon.timeDate} 11 | \alias{as.yearmon.jul} 12 | \alias{as.yearmon.POSIXt} 13 | \alias{as.yearmon.character} 14 | \alias{as.yearmon.factor} 15 | \alias{as.Date} 16 | \alias{as.Date.numeric} 17 | \alias{as.Date.ts} 18 | \alias{as.Date.yearmon} 19 | \alias{as.POSIXct.yearmon} 20 | \alias{as.POSIXlt.yearmon} 21 | \alias{as.list.yearmon} 22 | \alias{as.numeric.yearmon} 23 | \alias{as.character.yearmon} 24 | \alias{as.data.frame.yearmon} 25 | \alias{c.yearmon} 26 | \alias{cycle.yearmon} 27 | \alias{format.yearmon} 28 | \alias{is.numeric.yearmon} 29 | \alias{mean.yearmon} 30 | \alias{print.yearmon} 31 | \alias{range.yearmon} 32 | \alias{summary.yearmon} 33 | \alias{unique.yearmon} 34 | \alias{[.yearmon} 35 | \alias{[[.yearmon} 36 | \alias{MATCH.yearmon} 37 | \alias{Ops.yearmon} 38 | \alias{Summary.yearmon} 39 | \alias{Sys.yearmon} 40 | \alias{-.yearmon} 41 | \alias{xtfrm.yearmon} 42 | 43 | \title{An Index Class for Monthly Data} 44 | \description{ 45 | \code{"yearmon"} is a class for representing monthly data. 46 | } 47 | \usage{ 48 | yearmon(x) 49 | } 50 | \arguments{ 51 | \item{x}{numeric (interpreted as being \dQuote{in years}).} 52 | } 53 | \details{ 54 | The \code{"yearmon"} class is used to represent monthly data. Internally it holds 55 | the data as year plus 0 for January, 1/12 for February, 2/12 for March 56 | and so on in order that its internal representation is the same as 57 | \code{ts} class with \code{frequency = 12}. If \code{x} is not in this 58 | format it is rounded via \code{floor(12*x + .0001)/12}. 59 | 60 | There are coercion methods available for various classes including: 61 | default coercion to \code{"yearmon"} (which coerces to \code{"numeric"} first) 62 | and coercions to and from \code{"yearmon"} to \code{"Date"} (see below), 63 | \code{"POSIXct"}, 64 | \code{"POSIXlt"}, \code{"numeric"}, \code{"character"} and \code{"jul"}. 65 | The last one is from the \code{"tis"} package available on CRAN. 66 | In the case of \code{as.yearmon.POSIXt} the conversion is with respect to 67 | GMT. (Use \code{as.yearmon(format(...))} for other time zones.) 68 | In the case of 69 | \code{as.yearmon.character} the \code{format} argument uses the same 70 | percent code as 71 | \code{"Date"}. These are described in \code{\link{strptime}}. Unlike 72 | \code{"Date"} one can specify a year and month with no day. 73 | Default formats of \code{"\%Y-\%m"}, \code{"\%Y-\%m-\%d"} and \code{"\%b \%Y"}. 74 | 75 | There is an \code{is.numeric} method which returns \code{FALSE}. 76 | 77 | \code{as.Date.yearmon} and \code{as.yearmon.yearqtr} 78 | each has an optional 79 | second argument of \code{"frac"} which is a number between 0 and 1 inclusive 80 | that indicates the fraction of the way through the period that the result 81 | represents. The default is 0 which means the beginning of the period. 82 | 83 | There is also a \code{date} method for \code{as.yearmon} usable with objects 84 | created with package \code{date}. 85 | 86 | \code{Sys.yearmon()} returns the current year/month and methods for 87 | \code{min}, \code{max} and \code{range} are defined (by defining 88 | a method for \code{Summary}). 89 | 90 | A \code{yearmon} \code{mean} method is also defined. 91 | } 92 | 93 | \value{ 94 | Returns its argument converted to class \code{yearmon}. 95 | } 96 | 97 | \seealso{\code{\link{yearqtr}}, \code{\link{zoo}}, \code{\link{zooreg}}, \code{\link{ts}}} 98 | 99 | \examples{ 100 | Sys.setenv(TZ = "GMT") 101 | 102 | x <- as.yearmon(2000 + seq(0, 23)/12) 103 | x 104 | 105 | as.yearmon("mar07", "\%b\%y") 106 | as.yearmon("2007-03-01") 107 | as.yearmon("2007-12") 108 | 109 | # returned Date is the fraction of the way through 110 | # the period given by frac (= 0 by default) 111 | as.Date(x) 112 | as.Date(x, frac = 1) 113 | as.POSIXct(x) 114 | 115 | # given a Date, x, return the Date of the next Friday 116 | nextfri <- function(x) 7 * ceiling(as.numeric(x - 1)/7) + as.Date(1) 117 | 118 | # given a Date, d, return the same Date in the following month 119 | # Note that as.Date.yearmon gives first Date of the month. 120 | d <- as.Date("2005-1-1") + seq(0,90,30) 121 | next.month <- function(d) as.Date(as.yearmon(d) + 1/12) + 122 | as.numeric(d - as.Date(as.yearmon(d))) 123 | next.month(d) 124 | 125 | # 3rd Friday in last month of the quarter of Date x 126 | ## first day of last month of quarter 127 | y <- as.Date(zoo::as.yearmon(zoo::as.yearqtr(x), frac = 1)) 128 | ## number of days to first Friday 129 | n <- sapply(y, function(z) which(format(z + 0:6, "\%w") == "5")) - 1 130 | ## add number of days to third Friday 131 | y + n + 14 132 | 133 | 134 | suppressWarnings(RNGversion("3.5.0")) 135 | set.seed(1) 136 | 137 | z <- zoo(rnorm(24), x, frequency = 12) 138 | z 139 | as.ts(z) 140 | 141 | ## convert data fram to multivariate monthly "ts" series 142 | ## 1.read raw data 143 | Lines.raw <- "ID Date Count 144 | 123 20 May 1999 1 145 | 123 21 May 1999 3 146 | 222 1 Feb 2000 2 147 | 222 3 Feb 2000 4 148 | " 149 | DF <- read.table(text = Lines.raw, skip = 1, 150 | col.names = c("ID", "d", "b", "Y", "Count")) 151 | ## 2. fix raw date 152 | DF$yearmon <- as.yearmon(paste(DF$b, DF$Y), "\%b \%Y") 153 | ## 3. aggregate counts over months, convert to zoo and merge over IDs 154 | ag <- function(DF) aggregate(zoo(DF$Count), DF$yearmon, sum) 155 | z <- do.call("merge.zoo", lapply(split(DF, DF$ID), ag)) 156 | ## 4. convert to "zooreg" and then to "ts" 157 | frequency(z) <- 12 158 | as.ts(z) 159 | 160 | xx <- zoo(seq_along(x), x) 161 | 162 | ## aggregating over year 163 | as.year <- function(x) as.numeric(floor(as.yearmon(x))) 164 | aggregate(xx, as.year, mean) 165 | 166 | } 167 | \keyword{ts} 168 | -------------------------------------------------------------------------------- /man/yearqtr.Rd: -------------------------------------------------------------------------------- 1 | \name{yearqtr} 2 | \alias{yearqtr} 3 | \alias{as.yearqtr} 4 | \alias{as.yearqtr.default} 5 | \alias{as.yearqtr.numeric} 6 | \alias{as.yearqtr.integer} 7 | \alias{as.yearqtr.date} 8 | \alias{as.yearqtr.dates} 9 | \alias{as.yearqtr.Date} 10 | \alias{as.yearqtr.timeDate} 11 | \alias{as.yearqtr.jul} 12 | \alias{as.yearqtr.POSIXt} 13 | \alias{as.yearqtr.character} 14 | \alias{as.yearqtr.factor} 15 | \alias{as.yearqtr.yearqtr} 16 | \alias{as.Date.yearqtr} 17 | \alias{as.POSIXct.yearqtr} 18 | \alias{as.POSIXlt.yearqtr} 19 | \alias{as.list.yearqtr} 20 | \alias{as.numeric.yearqtr} 21 | \alias{as.character.yearqtr} 22 | \alias{as.data.frame.yearqtr} 23 | \alias{c.yearqtr} 24 | \alias{cycle.yearqtr} 25 | \alias{format.yearqtr} 26 | \alias{is.numeric.yearqtr} 27 | \alias{mean.yearqtr} 28 | \alias{print.yearqtr} 29 | \alias{range.yearqtr} 30 | \alias{summary.yearqtr} 31 | \alias{unique.yearqtr} 32 | \alias{[.yearqtr} 33 | \alias{[[.yearqtr} 34 | \alias{MATCH.yearqtr} 35 | \alias{Ops.yearqtr} 36 | \alias{Summary.yearqtr} 37 | \alias{Sys.yearqtr} 38 | \alias{-.yearqtr} 39 | \alias{xtfrm.yearqtr} 40 | 41 | \title{An Index Class for Quarterly Data} 42 | \description{ 43 | \code{"yearqtr"} is a class for representing quarterly data. 44 | } 45 | 46 | \usage{ 47 | yearqtr(x) 48 | as.yearqtr(x, \dots) 49 | \method{as.yearqtr}{character}(x, format, \dots) 50 | \method{format}{yearqtr}(x, format = "\%Y Q\%q", \dots) 51 | } 52 | 53 | \arguments{ 54 | \item{x}{for \code{yearqtr} a numeric (interpreted as being 55 | \dQuote{in years}). For \code{as.yearqtr} another date class 56 | object. For the \code{"yearqtr"} method of \code{format} an 57 | object of class \code{"yearqtr"} or if called as \code{format.yearqtr} 58 | then an object with an \code{as.yearqtr} method that can be coerced 59 | to \code{"yearqtr"}.} 60 | \item{format}{character string specifying format. For coercing to \code{"yearqtr"} 61 | from character: \code{"\%Y"} and \code{"\%q"} have to be specified. For formatting an existing 62 | \code{"yearqtr"}: \code{"\%C"}, \code{"\%Y"}, \code{"\%y"} and \code{"\%q"}, if present, 63 | are replaced with the century, year, last two digits of the year, 64 | and quarter (i.e. a number between 1 and 4), respectively.} 65 | \item{\dots}{arguments passed ot other methods.} 66 | } 67 | 68 | \details{ 69 | The \code{"yearqtr"} class is used to represent quarterly data. Internally it holds 70 | the data as year plus 0 for Quarter 1, 1/4 for Quarter 2 71 | and so on in order that its internal representation is the same as 72 | \code{ts} class with \code{frequency = 4}. If \code{x} is not in this 73 | format it is rounded via \code{floor(4*x + .0001)/4}. 74 | 75 | \code{as.yearqtr.character} uses a default format of \code{"\%Y Q\%q"}, 76 | \code{"\%Y q\%q"} or \code{"\%Y-\%q"} according to whichever matches. 77 | \code{\%q} accepts the numbers 1-4 (possibly with leading zeros). Due to 78 | this \code{\%q} does not match to single digits only and consequently 79 | formats such as \code{as.yearqtr("Q12000", "Q\%q\%Y")} are ambiguous and 80 | do not work (i.e., result in \code{NA}). 81 | 82 | There are coercion methods available for various classes including: 83 | default coercion to \code{"yearqtr"} (which coerces to \code{"numeric"} first) 84 | and coercion from \code{"yearqtr"} to \code{"Date"} (see below), \code{"POSIXct"}, 85 | \code{"POSIXlt"}, \code{"numeric"}, \code{"character"} and \code{"jul"}. 86 | The last one is from the \code{frame} package on CRAN. 87 | 88 | There is an \code{is.numeric} method which returns \code{FALSE}. 89 | 90 | There is also a \code{date} method for \code{as.yearqtr} usable with objects 91 | created with package \code{date}. 92 | 93 | \code{Sys.yearqtr()} returns the current year/month and methods for 94 | \code{min}, \code{max} and \code{range} are defined (by defining 95 | a method for \code{Summary}). 96 | 97 | A \code{yearqtr} \code{mean} method is also defined. 98 | 99 | Certain methods support a \code{frac} argument. See \code{\link{yearmon}}. 100 | 101 | } 102 | \value{ 103 | \code{yearqtr} and \code{as.yearqtr} return the first argument converted to 104 | class \code{yearqtr}. 105 | The \code{format} method returns a character string representation of 106 | its argument first argument. 107 | } 108 | 109 | \seealso{\code{\link{yearmon}}, \code{\link{zoo}}, \code{\link{zooreg}}, \code{\link{ts}}, 110 | \code{\link{strptime}}.} 111 | 112 | \examples{ 113 | Sys.setenv(TZ = "GMT") 114 | 115 | x <- as.yearqtr(2000 + seq(0, 7)/4) 116 | x 117 | 118 | format(x, "\%Y Quarter \%q") 119 | as.yearqtr("2001 Q2") 120 | as.yearqtr("2001 q2") # same 121 | as.yearqtr("2001-2") # same 122 | 123 | # returned Date is the fraction of the way through 124 | # the period given by frac (= 0 by default) 125 | dd <- as.Date(x) 126 | format.yearqtr(dd) 127 | as.Date(x, frac = 1) 128 | as.POSIXct(x) 129 | 130 | suppressWarnings(RNGversion("3.5.0")) 131 | set.seed(1) 132 | 133 | zz <- zoo(rnorm(8), x, frequency = 4) 134 | zz 135 | as.ts(zz) 136 | 137 | } 138 | \keyword{ts} 139 | -------------------------------------------------------------------------------- /src/Makevars: -------------------------------------------------------------------------------- 1 | PKG_CPPFLAGS = -I../inst/include 2 | -------------------------------------------------------------------------------- /src/Makevars.win: -------------------------------------------------------------------------------- 1 | PKG_CPPFLAGS = -I../inst/include 2 | -------------------------------------------------------------------------------- /src/coredata.c: -------------------------------------------------------------------------------- 1 | /* 2 | # zoo: 3 | # 4 | # Copyright (C) 2008 Jeffrey A. Ryan jeff.a.ryan @ gmail.com 5 | # 6 | # Contributions from Joshua M. Ulrich 7 | # 8 | # This program is free software: you can redistribute it and/or modify 9 | # it under the terms of the GNU General Public License as published by 10 | # the Free Software Foundation, either version 2 of the License, or 11 | # (at your option) any later version. 12 | # 13 | # This program is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU General Public License 19 | # along with this program. If not, see . 20 | */ 21 | 22 | 23 | #include 24 | #include 25 | 26 | SEXP zoo_coredata (SEXP x, SEXP copyAttr) 27 | { 28 | /* copyAttr is a LGLSXP flag to indicate whether all 29 | attributes are to be left intact. This provides 30 | compatability with xts, by stripping all attributes 31 | if desired, without the overhead or adding then 32 | removing 33 | */ 34 | SEXP result; 35 | R_xlen_t i, j, ncs, nrs; 36 | int P=0; 37 | PROTECT(result = allocVector(TYPEOF(x), xlength(x))); P++; 38 | switch( TYPEOF(x)) { 39 | case REALSXP: 40 | memcpy(REAL(result), REAL(x), xlength(result) * sizeof(double)); 41 | break; 42 | case INTSXP: 43 | memcpy(INTEGER(result), INTEGER(x), xlength(result) * sizeof(int)); 44 | break; 45 | case LGLSXP: 46 | memcpy(LOGICAL(result), LOGICAL(x), xlength(result) * sizeof(int)); 47 | break; 48 | case CPLXSXP: 49 | memcpy(COMPLEX(result), COMPLEX(x), xlength(result) * sizeof(Rcomplex)); 50 | break; 51 | case STRSXP: 52 | ncs = ncols(x); nrs = nrows(x); 53 | for(j=0; j< ncs; j++) 54 | for(i=0; i< nrs; i++) 55 | SET_STRING_ELT(result, i+j*nrs, STRING_ELT(x, i+j*nrs)); 56 | break; 57 | case RAWSXP: 58 | memcpy(RAW(result), RAW(x), xlength(result) * sizeof(unsigned char)); 59 | break; 60 | default: 61 | error("currently unsupported data type"); 62 | break; 63 | } 64 | if( !isNull(getAttrib(x, R_DimSymbol))) { 65 | setAttrib(result, R_DimSymbol, getAttrib(x, R_DimSymbol)); 66 | if( !isNull(getAttrib(x, R_DimNamesSymbol)) ) { 67 | setAttrib(result, R_DimNamesSymbol, getAttrib(x,R_DimNamesSymbol)); 68 | } 69 | } else { 70 | setAttrib(result, R_NamesSymbol, getAttrib(x, R_NamesSymbol)); 71 | } 72 | if( asLogical(copyAttr)) { 73 | copyMostAttrib(x,result); 74 | SEXP oclass = PROTECT(getAttrib(x, install("oclass"))); P++; 75 | setAttrib(result, install("class"), oclass); 76 | } 77 | setAttrib(result, install("index"), R_NilValue); 78 | setAttrib(result, install("oclass"), R_NilValue); 79 | setAttrib(result, install("frequency"), R_NilValue); 80 | 81 | UNPROTECT(P); 82 | return result; 83 | } 84 | -------------------------------------------------------------------------------- /src/init.c: -------------------------------------------------------------------------------- 1 | /* 2 | # xts: eXtensible time-series 3 | # 4 | # Copyright (C) 2010 Jeffrey A. Ryan jeff.a.ryan @ gmail.com 5 | # 6 | # Contributions from Joshua M. Ulrich 7 | # 8 | # This program is free software: you can redistribute it and/or modify 9 | # it under the terms of the GNU General Public License as published by 10 | # the Free Software Foundation, either version 2 of the License, or 11 | # (at your option) any later version. 12 | # 13 | # This program is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU General Public License 19 | # along with this program. If not, see . 20 | */ 21 | 22 | 23 | #include 24 | #include 25 | 26 | static const 27 | R_CallMethodDef callMethods[] = { 28 | {"zoo_lag", (DL_FUNC) &zoo_lag, 3}, 29 | {"zoo_coredata", (DL_FUNC) &zoo_coredata, 2}, 30 | {NULL, NULL, 0} 31 | }; 32 | 33 | void R_init_zoo(DllInfo *info) 34 | { 35 | R_registerRoutines(info, 36 | NULL, 37 | callMethods, 38 | NULL, 39 | NULL); 40 | 41 | R_useDynamicSymbols(info, FALSE); 42 | #define RegisterZoo(routine) R_RegisterCCallable("zoo",#routine,(DL_FUNC) &routine) 43 | 44 | /* used by external packages linking to internal xts code from C */ 45 | R_RegisterCCallable("zoo","zoo_lag",(DL_FUNC) &zoo_lag); 46 | R_RegisterCCallable("zoo","zoo_coredata",(DL_FUNC) &zoo_coredata); 47 | } 48 | -------------------------------------------------------------------------------- /tests/as.Date.R: -------------------------------------------------------------------------------- 1 | ## set Z's timezone for reproducibility 2 | Sys.setenv(TZ = "Europe/Vienna") 3 | 4 | ## base results 5 | as.Date(10957, origin = "1970-01-01") 6 | as.Date("2000-01-01") 7 | as.Date(as.POSIXct("2000-01-01 00:00:00 GMT", tz = "GMT")) 8 | as.Date(as.POSIXlt("2000-01-01 00:00:00 GMT", tz = "GMT")) 9 | as.Date(NA) 10 | 11 | ## for chron objects 12 | library("chron") 13 | as.Date(dates("01/01/2000")) 14 | as.Date(chron("01/01/2000", "00:00:00")) 15 | 16 | ## for tis objects 17 | library("tis") 18 | as.Date(ti(20000101, "daily")) 19 | as.Date(jul(20000101)) 20 | 21 | ## for timeDate objects 22 | library("timeDate") 23 | as.Date(timeDate("2000-01-01")) 24 | 25 | ## with zoo attached (masking as.Date/as.Date.numeric) 26 | library("zoo") 27 | as.Date(10957) 28 | as.Date("2000-01-01") 29 | as.Date(as.POSIXct("2000-01-01 00:00:00 GMT", tz = "GMT")) 30 | as.Date(as.POSIXlt("2000-01-01 00:00:00 GMT", tz = "GMT")) 31 | as.Date(NA) 32 | as.Date(yearmon(2000)) 33 | as.Date(yearqtr(2000)) 34 | as.Date(dates("01/01/2000")) 35 | as.Date(chron("01/01/2000", "00:00:00")) 36 | as.Date.ti <- tis:::as.Date.ti ## filed request for export 37 | as.Date(ti(20000101, "daily")) 38 | as.Date.jul <- tis:::as.Date.jul ## filed request for export 39 | as.Date(jul(20000101)) 40 | as.Date.timeDate <- timeDate:::as.Date.timeDate ## filed request for export 41 | as.Date(timeDate("2000-01-01")) 42 | 43 | ## with mondate attached (masking again as.Date) 44 | library("mondate") 45 | as.Date(10957) 46 | as.Date("2000-01-01") 47 | as.Date(as.POSIXct("2000-01-01 00:00:00 GMT", tz = "GMT")) 48 | as.Date(as.POSIXlt("2000-01-01 00:00:00 GMT", tz = "GMT")) 49 | as.Date(NA) 50 | as.Date(yearmon(2000)) 51 | as.Date(yearqtr(2000)) 52 | as.Date(dates("01/01/2000")) 53 | as.Date(chron("01/01/2000", "00:00:00")) 54 | as.Date(ti(20000101, "daily")) 55 | as.Date(jul(20000101)) 56 | as.Date(timeDate("2000-01-01")) 57 | as.Date(mondate(1/31)) 58 | 59 | -------------------------------------------------------------------------------- /tests/as.Date.Rout.save: -------------------------------------------------------------------------------- 1 | 2 | R version 4.0.4 (2021-02-15) -- "Lost Library Book" 3 | Copyright (C) 2021 The R Foundation for Statistical Computing 4 | Platform: x86_64-pc-linux-gnu (64-bit) 5 | 6 | R is free software and comes with ABSOLUTELY NO WARRANTY. 7 | You are welcome to redistribute it under certain conditions. 8 | Type 'license()' or 'licence()' for distribution details. 9 | 10 | R is a collaborative project with many contributors. 11 | Type 'contributors()' for more information and 12 | 'citation()' on how to cite R or R packages in publications. 13 | 14 | Type 'demo()' for some demos, 'help()' for on-line help, or 15 | 'help.start()' for an HTML browser interface to help. 16 | Type 'q()' to quit R. 17 | 18 | > ## set Z's timezone for reproducibility 19 | > Sys.setenv(TZ = "Europe/Vienna") 20 | > 21 | > ## base results 22 | > as.Date(10957, origin = "1970-01-01") 23 | [1] "2000-01-01" 24 | > as.Date("2000-01-01") 25 | [1] "2000-01-01" 26 | > as.Date(as.POSIXct("2000-01-01 00:00:00 GMT", tz = "GMT")) 27 | [1] "2000-01-01" 28 | > as.Date(as.POSIXlt("2000-01-01 00:00:00 GMT", tz = "GMT")) 29 | [1] "2000-01-01" 30 | > as.Date(NA) 31 | [1] NA 32 | > 33 | > ## for chron objects 34 | > library("chron") 35 | > as.Date(dates("01/01/2000")) 36 | [1] "2000-01-01" 37 | > as.Date(chron("01/01/2000", "00:00:00")) 38 | [1] "2000-01-01" 39 | > 40 | > ## for tis objects 41 | > library("tis") 42 | > as.Date(ti(20000101, "daily")) 43 | [1] "2000-01-01" 44 | > as.Date(jul(20000101)) 45 | [1] "2000-01-01" 46 | > 47 | > ## for timeDate objects 48 | > library("timeDate") 49 | 50 | Attaching package: 'timeDate' 51 | 52 | The following objects are masked from 'package:tis': 53 | 54 | dayOfWeek, dayOfYear, isHoliday 55 | 56 | > as.Date(timeDate("2000-01-01")) 57 | [1] "2000-01-01" 58 | > 59 | > ## with zoo attached (masking as.Date/as.Date.numeric) 60 | > library("zoo") 61 | 62 | Attaching package: 'zoo' 63 | 64 | The following objects are masked from 'package:base': 65 | 66 | as.Date, as.Date.numeric 67 | 68 | > as.Date(10957) 69 | [1] "2000-01-01" 70 | > as.Date("2000-01-01") 71 | [1] "2000-01-01" 72 | > as.Date(as.POSIXct("2000-01-01 00:00:00 GMT", tz = "GMT")) 73 | [1] "2000-01-01" 74 | > as.Date(as.POSIXlt("2000-01-01 00:00:00 GMT", tz = "GMT")) 75 | [1] "2000-01-01" 76 | > as.Date(NA) 77 | [1] NA 78 | > as.Date(yearmon(2000)) 79 | [1] "2000-01-01" 80 | > as.Date(yearqtr(2000)) 81 | [1] "2000-01-01" 82 | > as.Date(dates("01/01/2000")) 83 | [1] "2000-01-01" 84 | > as.Date(chron("01/01/2000", "00:00:00")) 85 | [1] "2000-01-01" 86 | > as.Date.ti <- tis:::as.Date.ti ## filed request for export 87 | > as.Date(ti(20000101, "daily")) 88 | [1] "2000-01-01" 89 | > as.Date.jul <- tis:::as.Date.jul ## filed request for export 90 | > as.Date(jul(20000101)) 91 | [1] "2000-01-01" 92 | > as.Date.timeDate <- timeDate:::as.Date.timeDate ## filed request for export 93 | > as.Date(timeDate("2000-01-01")) 94 | [1] "2000-01-01" 95 | > 96 | > ## with mondate attached (masking again as.Date) 97 | > library("mondate") 98 | 99 | Attaching package: 'mondate' 100 | 101 | The following objects are masked from 'package:tis': 102 | 103 | day, month, quarter, year, ymd 104 | 105 | The following object is masked from 'package:base': 106 | 107 | as.difftime 108 | 109 | > as.Date(10957) 110 | [1] "2000-01-01" 111 | > as.Date("2000-01-01") 112 | [1] "2000-01-01" 113 | > as.Date(as.POSIXct("2000-01-01 00:00:00 GMT", tz = "GMT")) 114 | [1] "2000-01-01" 115 | > as.Date(as.POSIXlt("2000-01-01 00:00:00 GMT", tz = "GMT")) 116 | [1] "2000-01-01" 117 | > as.Date(NA) 118 | [1] NA 119 | > as.Date(yearmon(2000)) 120 | [1] "2000-01-01" 121 | > as.Date(yearqtr(2000)) 122 | [1] "2000-01-01" 123 | > as.Date(dates("01/01/2000")) 124 | [1] "2000-01-01" 125 | > as.Date(chron("01/01/2000", "00:00:00")) 126 | [1] "2000-01-01" 127 | > as.Date(ti(20000101, "daily")) 128 | [1] "2000-01-01" 129 | > as.Date(jul(20000101)) 130 | [1] "2000-01-01" 131 | > as.Date(timeDate("2000-01-01")) 132 | [1] "2000-01-01" 133 | > as.Date(mondate(1/31)) 134 | [1] "2000-01-01" 135 | > 136 | > 137 | > proc.time() 138 | user system elapsed 139 | 0.491 0.028 0.512 140 | -------------------------------------------------------------------------------- /tests/bugfixes.R: -------------------------------------------------------------------------------- 1 | ## packages 2 | library("zoo") 3 | library("timeDate") 4 | 5 | ## aggregate() with "timeDate" index 6 | z <- zoo(1:3, timeDate(c("2011-09-19 12:00", "2011-09-19 12:00", "2011-09-19 13:00"))) 7 | aggregate(z, identity, mean) 8 | 9 | ## assignment and preservation of column names in merge() 10 | x <- zoo(cbind(a = 3:4, b = 5:6)) 11 | y <- zoo(1:2) 12 | merge(x, zoo(, time(x))) 13 | merge(y, x) 14 | 15 | ## [<-.zoo with logical row index 16 | z <- zoo(cbind(1:5, 11:15), 101:105) 17 | z[index(z) == 103, 1] <- 0 18 | 19 | ## rollapply(..., mean, partial = TRUE) 20 | z <- zoo(11:15) 21 | identical(rollapply(z, 3, mean, partial = TRUE), 22 | rollapply(z, 3, (mean), partial = TRUE)) 23 | 24 | ## rollmedian(..., k = 1) 25 | z <- zoo(sin(0:20)) 26 | identical(z, rollmedian(z, 1)) 27 | identical(coredata(rollmedian(z, 1)), as.vector(runmed(coredata(z), 1))) 28 | 29 | ## na.fill with just NAs (directly and implicitly through rollapply) 30 | na.fill(c(NA, NA), fill = NA) 31 | rollapply(1:2, 3, sum, fill = NA) 32 | -------------------------------------------------------------------------------- /tests/bugfixes.Rout.save: -------------------------------------------------------------------------------- 1 | 2 | R version 3.1.1 (2014-07-10) -- "Sock it to Me" 3 | Copyright (C) 2014 The R Foundation for Statistical Computing 4 | Platform: x86_64-pc-linux-gnu (64-bit) 5 | 6 | R is free software and comes with ABSOLUTELY NO WARRANTY. 7 | You are welcome to redistribute it under certain conditions. 8 | Type 'license()' or 'licence()' for distribution details. 9 | 10 | R is a collaborative project with many contributors. 11 | Type 'contributors()' for more information and 12 | 'citation()' on how to cite R or R packages in publications. 13 | 14 | Type 'demo()' for some demos, 'help()' for on-line help, or 15 | 'help.start()' for an HTML browser interface to help. 16 | Type 'q()' to quit R. 17 | 18 | > ## packages 19 | > library("zoo") 20 | 21 | Attaching package: 'zoo' 22 | 23 | The following objects are masked from 'package:base': 24 | 25 | as.Date, as.Date.numeric 26 | 27 | > library("timeDate") 28 | > 29 | > ## aggregate() with "timeDate" index 30 | > z <- zoo(1:3, timeDate(c("2011-09-19 12:00", "2011-09-19 12:00", "2011-09-19 13:00"))) 31 | Warning message: 32 | In zoo(1:3, timeDate(c("2011-09-19 12:00", "2011-09-19 12:00", "2011-09-19 13:00"))) : 33 | some methods for "zoo" objects do not work if the index entries in 'order.by' are not unique 34 | > aggregate(z, identity, mean) 35 | 2011-09-19 12:00:00 2011-09-19 13:00:00 36 | 1.5 3.0 37 | > 38 | > ## assignment and preservation of column names in merge() 39 | > x <- zoo(cbind(a = 3:4, b = 5:6)) 40 | > y <- zoo(1:2) 41 | > merge(x, zoo(, time(x))) 42 | a b 43 | 1 3 5 44 | 2 4 6 45 | > merge(y, x) 46 | y a b 47 | 1 1 3 5 48 | 2 2 4 6 49 | > 50 | > ## [<-.zoo with logical row index 51 | > z <- zoo(cbind(1:5, 11:15), 101:105) 52 | > z[index(z) == 103, 1] <- 0 53 | > 54 | > ## rollapply(..., mean, partial = TRUE) 55 | > z <- zoo(11:15) 56 | > identical(rollapply(z, 3, mean, partial = TRUE), 57 | + rollapply(z, 3, (mean), partial = TRUE)) 58 | [1] TRUE 59 | > 60 | > ## rollmedian(..., k = 1) 61 | > z <- zoo(sin(0:20)) 62 | > identical(z, rollmedian(z, 1)) 63 | [1] TRUE 64 | > identical(coredata(rollmedian(z, 1)), as.vector(runmed(coredata(z), 1))) 65 | [1] TRUE 66 | > 67 | > ## na.fill with just NAs (directly and implicitly through rollapply) 68 | > na.fill(c(NA, NA), fill = NA) 69 | [1] NA NA 70 | > rollapply(1:2, 3, sum, fill = NA) 71 | [1] NA NA 72 | > 73 | > proc.time() 74 | user system elapsed 75 | 1.044 0.036 1.072 76 | -------------------------------------------------------------------------------- /tests/na.fill.R: -------------------------------------------------------------------------------- 1 | library("zoo") 2 | 3 | target <- c(100, 1, 200, 2, 300) 4 | current <- na.fill0(c(NA, 1, NA, 2, NA), c(100, 200, 300)) 5 | identical(target, current) 6 | 7 | target <- structure(c(100, 1, 200, 2), na.action = 5L) 8 | current <- na.fill0(c(NA, 1, NA, 2, NA), list(100, 200, NULL)) 9 | identical(target, current) 10 | 11 | target <- structure(c(1, 1, 200, 2), na.action = 5L) 12 | current <- na.fill0(c(NA, 1, NA, 2, NA), list("extend", 200, NULL)) 13 | identical(target, current) 14 | 15 | target <- c(1, 1, 200, 2, 2) 16 | current <- na.fill0(c(NA, 1, NA, 2, NA), list("extend", 200, "extend")) 17 | identical(target, current) 18 | 19 | target <- structure(c(1, 2), na.action = c(1L, 3L, 5L)) 20 | current <- na.fill0(c(NA, 1, NA, 2, NA), list()) 21 | identical(target, current) 22 | 23 | target <- NULL 24 | current <- na.fill0(NULL, list(1)) 25 | identical(target, current) 26 | 27 | target <- 1 28 | current <- na.fill0(1, list(1)) 29 | identical(target, current) 30 | 31 | target <- 1 32 | current <- na.fill0(1, 2) 33 | identical(target, current) 34 | 35 | target <- structure(c(17650, 17650, 0, 17651, 17651), class = "Date") 36 | current <- na.fill0(as.Date("2018-04-28") + c(NA, 1, NA, 2, NA), list("extend", as.Date(0))) 37 | identical(target, current) 38 | 39 | target <- structure(c(0, 17650, 0, 17651, 0), class = "Date") 40 | current <- na.fill0(as.Date("2018-04-28") + c(NA, 1, NA, 2, NA), as.Date(0)) 41 | identical(target, current) 42 | -------------------------------------------------------------------------------- /tests/na.fill.Rout.save: -------------------------------------------------------------------------------- 1 | 2 | R version 3.4.4 (2018-03-15) -- "Someone to Lean On" 3 | Copyright (C) 2018 The R Foundation for Statistical Computing 4 | Platform: x86_64-pc-linux-gnu (64-bit) 5 | 6 | R is free software and comes with ABSOLUTELY NO WARRANTY. 7 | You are welcome to redistribute it under certain conditions. 8 | Type 'license()' or 'licence()' for distribution details. 9 | 10 | R is a collaborative project with many contributors. 11 | Type 'contributors()' for more information and 12 | 'citation()' on how to cite R or R packages in publications. 13 | 14 | Type 'demo()' for some demos, 'help()' for on-line help, or 15 | 'help.start()' for an HTML browser interface to help. 16 | Type 'q()' to quit R. 17 | 18 | > library("zoo") 19 | 20 | Attaching package: 'zoo' 21 | 22 | The following objects are masked from 'package:base': 23 | 24 | as.Date, as.Date.numeric 25 | 26 | > 27 | > target <- c(100, 1, 200, 2, 300) 28 | > current <- na.fill0(c(NA, 1, NA, 2, NA), c(100, 200, 300)) 29 | > identical(target, current) 30 | [1] TRUE 31 | > 32 | > target <- structure(c(100, 1, 200, 2), na.action = 5L) 33 | > current <- na.fill0(c(NA, 1, NA, 2, NA), list(100, 200, NULL)) 34 | > identical(target, current) 35 | [1] TRUE 36 | > 37 | > target <- structure(c(1, 1, 200, 2), na.action = 5L) 38 | > current <- na.fill0(c(NA, 1, NA, 2, NA), list("extend", 200, NULL)) 39 | > identical(target, current) 40 | [1] TRUE 41 | > 42 | > target <- c(1, 1, 200, 2, 2) 43 | > current <- na.fill0(c(NA, 1, NA, 2, NA), list("extend", 200, "extend")) 44 | > identical(target, current) 45 | [1] TRUE 46 | > 47 | > target <- structure(c(1, 2), na.action = c(1L, 3L, 5L)) 48 | > current <- na.fill0(c(NA, 1, NA, 2, NA), list()) 49 | > identical(target, current) 50 | [1] TRUE 51 | > 52 | > target <- NULL 53 | > current <- na.fill0(NULL, list(1)) 54 | > identical(target, current) 55 | [1] TRUE 56 | > 57 | > target <- 1 58 | > current <- na.fill0(1, list(1)) 59 | > identical(target, current) 60 | [1] TRUE 61 | > 62 | > target <- 1 63 | > current <- na.fill0(1, 2) 64 | > identical(target, current) 65 | [1] TRUE 66 | > 67 | > target <- structure(c(17650, 17650, 0, 17651, 17651), class = "Date") 68 | > current <- na.fill0(as.Date("2018-04-28") + c(NA, 1, NA, 2, NA), list("extend", as.Date(0))) 69 | > identical(target, current) 70 | [1] TRUE 71 | > 72 | > target <- structure(c(0, 17650, 0, 17651, 0), class = "Date") 73 | > current <- na.fill0(as.Date("2018-04-28") + c(NA, 1, NA, 2, NA), as.Date(0)) 74 | > identical(target, current) 75 | [1] TRUE 76 | > 77 | > proc.time() 78 | user system elapsed 79 | 0.199 0.036 0.224 80 | -------------------------------------------------------------------------------- /tests/na.locf.R: -------------------------------------------------------------------------------- 1 | library("zoo") 2 | 3 | x <- cbind( 4 | c(1, NA, 2, NA, NA, NA, NA, 3), 5 | c(NA, 1, NA, 2, NA, NA, NA, 3) 6 | ) 7 | na.locf(x) 8 | na.locf(x, fromLast = TRUE) 9 | na.locf(x, maxgap = 3) 10 | na.locf(x[,2]) 11 | na.locf(x[,2], na.rm = FALSE) 12 | 13 | z <- zoo(x, as.Date("2000-01-01") + 0:8) 14 | na.locf(z) 15 | na.locf(z, fromLast = TRUE) 16 | na.locf(z, maxgap = 3) 17 | na.locf(z[,2]) 18 | na.locf(z[,2], na.rm = FALSE) 19 | 20 | d <- as.Date("2000-01-01") + c(0, NA, 2, NA, NA, NA, NA, 7) 21 | na.locf(d) 22 | na.locf(d, fromLast = TRUE) 23 | na.locf(d, maxgap = 3) 24 | -------------------------------------------------------------------------------- /tests/na.locf.Rout.save: -------------------------------------------------------------------------------- 1 | 2 | R version 3.3.2 (2016-10-31) -- "Sincere Pumpkin Patch" 3 | Copyright (C) 2016 The R Foundation for Statistical Computing 4 | Platform: x86_64-pc-linux-gnu (64-bit) 5 | 6 | R is free software and comes with ABSOLUTELY NO WARRANTY. 7 | You are welcome to redistribute it under certain conditions. 8 | Type 'license()' or 'licence()' for distribution details. 9 | 10 | R is a collaborative project with many contributors. 11 | Type 'contributors()' for more information and 12 | 'citation()' on how to cite R or R packages in publications. 13 | 14 | Type 'demo()' for some demos, 'help()' for on-line help, or 15 | 'help.start()' for an HTML browser interface to help. 16 | Type 'q()' to quit R. 17 | 18 | > library("zoo") 19 | 20 | Attaching package: 'zoo' 21 | 22 | The following objects are masked from 'package:base': 23 | 24 | as.Date, as.Date.numeric 25 | 26 | > 27 | > x <- cbind( 28 | + c(1, NA, 2, NA, NA, NA, NA, 3), 29 | + c(NA, 1, NA, 2, NA, NA, NA, 3) 30 | + ) 31 | > na.locf(x) 32 | [,1] [,2] 33 | [1,] 1 NA 34 | [2,] 1 1 35 | [3,] 2 1 36 | [4,] 2 2 37 | [5,] 2 2 38 | [6,] 2 2 39 | [7,] 2 2 40 | [8,] 3 3 41 | > na.locf(x, fromLast = TRUE) 42 | [,1] [,2] 43 | [1,] 1 1 44 | [2,] 2 1 45 | [3,] 2 2 46 | [4,] 3 2 47 | [5,] 3 3 48 | [6,] 3 3 49 | [7,] 3 3 50 | [8,] 3 3 51 | > na.locf(x, maxgap = 3) 52 | [,1] [,2] 53 | [1,] 1 NA 54 | [2,] 1 1 55 | [3,] 2 1 56 | [4,] NA 2 57 | [5,] NA 2 58 | [6,] NA 2 59 | [7,] NA 2 60 | [8,] 3 3 61 | > na.locf(x[,2]) 62 | [1] 1 1 2 2 2 2 3 63 | > na.locf(x[,2], na.rm = FALSE) 64 | [1] NA 1 1 2 2 2 2 3 65 | > 66 | > z <- zoo(x, as.Date("2000-01-01") + 0:8) 67 | > na.locf(z) 68 | 69 | 2000-01-01 1 NA 70 | 2000-01-02 1 1 71 | 2000-01-03 2 1 72 | 2000-01-04 2 2 73 | 2000-01-05 2 2 74 | 2000-01-06 2 2 75 | 2000-01-07 2 2 76 | 2000-01-08 3 3 77 | 2000-01-09 1 3 78 | > na.locf(z, fromLast = TRUE) 79 | 80 | 2000-01-01 1 1 81 | 2000-01-02 2 1 82 | 2000-01-03 2 2 83 | 2000-01-04 3 2 84 | 2000-01-05 3 3 85 | 2000-01-06 3 3 86 | 2000-01-07 3 3 87 | 2000-01-08 3 3 88 | 2000-01-09 1 NA 89 | > na.locf(z, maxgap = 3) 90 | 91 | 2000-01-01 1 NA 92 | 2000-01-02 1 1 93 | 2000-01-03 2 1 94 | 2000-01-04 NA 2 95 | 2000-01-05 NA 2 96 | 2000-01-06 NA 2 97 | 2000-01-07 NA 2 98 | 2000-01-08 3 3 99 | 2000-01-09 1 3 100 | > na.locf(z[,2]) 101 | 2000-01-02 2000-01-03 2000-01-04 2000-01-05 2000-01-06 2000-01-07 2000-01-08 102 | 1 1 2 2 2 2 3 103 | 2000-01-09 104 | 3 105 | > na.locf(z[,2], na.rm = FALSE) 106 | 2000-01-01 2000-01-02 2000-01-03 2000-01-04 2000-01-05 2000-01-06 2000-01-07 107 | NA 1 1 2 2 2 2 108 | 2000-01-08 2000-01-09 109 | 3 3 110 | > 111 | > d <- as.Date("2000-01-01") + c(0, NA, 2, NA, NA, NA, NA, 7) 112 | > na.locf(d) 113 | [1] "2000-01-01" "2000-01-01" "2000-01-03" "2000-01-03" "2000-01-03" 114 | [6] "2000-01-03" "2000-01-03" "2000-01-08" 115 | > na.locf(d, fromLast = TRUE) 116 | [1] "2000-01-01" "2000-01-03" "2000-01-03" "2000-01-08" "2000-01-08" 117 | [6] "2000-01-08" "2000-01-08" "2000-01-08" 118 | > na.locf(d, maxgap = 3) 119 | [1] "2000-01-01" "2000-01-01" "2000-01-03" NA NA 120 | [6] NA NA "2000-01-08" 121 | > 122 | > proc.time() 123 | user system elapsed 124 | 0.196 0.024 0.216 125 | -------------------------------------------------------------------------------- /vignettes/.install_extras: -------------------------------------------------------------------------------- 1 | MSFT.rda$ 2 | msft2004.rda$ 3 | sunw.rda$ 4 | demo1.txt$ 5 | demo2.txt$ 6 | -------------------------------------------------------------------------------- /vignettes/MSFT.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cran/zoo/d032ed0519de3eeefe651ad9f25f7408461732a0/vignettes/MSFT.rda -------------------------------------------------------------------------------- /vignettes/demo1.txt: -------------------------------------------------------------------------------- 1 | 10 Feb 2005|43.78 2 | 11 Feb 2005|43.79 3 | 14 Feb 2005|43.72 4 | 15 Feb 2005|43.76 5 | 16 Feb 2005|43.82 6 | 17 Feb 2005|43.74 7 | 18 Feb 2005|43.84 8 | 21 Feb 2005|43.82 9 | 22 Feb 2005|43.72 10 | 23 Feb 2005|43.72 11 | 24 Feb 2005|43.70 12 | 25 Feb 2005|43.69 13 | 28 Feb 2005|43.64 14 | 01 Mar 2005|43.72 15 | 02 Mar 2005|43.70 16 | 03 Mar 2005|43.65 17 | 04 Mar 2005|43.71 18 | 07 Mar 2005|43.69 19 | 09 Mar 2005|43.67 20 | 10 Mar 2005|43.58 21 | -------------------------------------------------------------------------------- /vignettes/demo2.txt: -------------------------------------------------------------------------------- 1 | Daily,10 Feb 2005,2063.35,4379.20 2 | Daily,11 Feb 2005,2082.05,4382.90 3 | Daily,14 Feb 2005,2098.25,4391.15 4 | Daily,15 Feb 2005,2089.95,4367.25 5 | Daily,17 Feb 2005,2061.90,4320.15 6 | Daily,18 Feb 2005,2055.55,4318.15 7 | Daily,21 Feb 2005,2043.20,4262.25 8 | Daily,22 Feb 2005,2058.40,4326.10 9 | Daily,23 Feb 2005,2057.10,4346.00 10 | Daily,24 Feb 2005,2055.30,4337.00 11 | Daily,25 Feb 2005,2060.90,4305.75 12 | Daily,28 Feb 2005,2103.25,4388.20 13 | Daily,01 Mar 2005,2084.40,4382.25 14 | Daily,02 Mar 2005,2093.25,4470.00 15 | Daily,03 Mar 2005,2128.85,4515.80 16 | Daily,04 Mar 2005,2148.15,4549.55 17 | Daily,07 Mar 2005,2160.10,4618.05 18 | Daily,08 Mar 2005,2168.95,4666.70 19 | Daily,09 Mar 2005,2160.80,4623.85 20 | Daily,10 Mar 2005,2167.40,4648.05 21 | -------------------------------------------------------------------------------- /vignettes/msft2004.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cran/zoo/d032ed0519de3eeefe651ad9f25f7408461732a0/vignettes/msft2004.rda -------------------------------------------------------------------------------- /vignettes/sunw.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cran/zoo/d032ed0519de3eeefe651ad9f25f7408461732a0/vignettes/sunw.rda -------------------------------------------------------------------------------- /vignettes/zoo-design.Rnw: -------------------------------------------------------------------------------- 1 | \documentclass[article,nojss]{jss} 2 | %% need no \usepackage{Sweave} 3 | 4 | \title{\pkg{zoo} Design} 5 | \Plaintitle{zoo Design} 6 | 7 | \author{\pkg{zoo} Development Team} 8 | \Plainauthor{zoo Development Team} 9 | 10 | \Address{ 11 | \pkg{zoo} Development Team\\ 12 | \proglang{R}-Forge: \url{http://R-Forge.R-project.org/projects/zoo/}\\ 13 | Comprehensive \proglang{R} Archive Network: \url{http://CRAN.R-project.org/package=zoo} 14 | } 15 | 16 | \Keywords{irregular time series, ordered observations, time index} 17 | 18 | \Abstract{ 19 | This is a set of design principles that -- albeit not having been explicitly set out 20 | initially -- have guided the development of the \proglang{R} \pkg{zoo} package. 21 | } 22 | 23 | \begin{document} 24 | 25 | \SweaveOpts{engine=R,eps=FALSE} 26 | %\VignetteIndexEntry{zoo Design} 27 | %\VignetteDepends{zoo} 28 | %\VignetteKeywords{irregular time series, ordered observations, time index} 29 | %\VignettePackage{zoo} 30 | 31 | 32 | <>= 33 | library("zoo") 34 | Sys.setenv(TZ = "GMT") 35 | @ 36 | 37 | \emph{\pkg{zoo} works with any ordered index class} having the prescribed 38 | methods, see \code{?zoo} and \cite{zoo:Zeileis+Grothendieck:2005}. 39 | Specific index classes are not hard-coded in functions (with 40 | a few exceptions necessitated by external interfaces such as reading 41 | and interfacing with `\code{ts}') but rather all index operations are only done 42 | via the allowed methods. 43 | 44 | \emph{\pkg{zoo} is invisible}. As far as possible new names (e.g., for functions or methods 45 | and their arguments) are not introduced. 46 | New functionality is added as methods to generics from base \proglang{R} 47 | allowing reuse of those names. When names are added, thought is put 48 | into the name since \pkg{zoo} is so miserly about adding them. For example, 49 | the \code{read.zoo} name is obviously derived from \code{read.table} and the names 50 | \code{na.locf} or \code{na.approx} are in analogy to other \code{na.*} functions 51 | frome base \proglang{R}. 52 | 53 | \emph{\pkg{zoo} is consistent with base \proglang{R}}. The idea is to make the usage 54 | of \pkg{zoo} completely natural to someone who already has experience with \proglang{R} 55 | (in particular with the `\code{ts}' class). Certainly, \pkg{zoo} contains extensions 56 | to base \proglang{R}, but they should be as consistent as possible and have a natural 57 | `look and feel'. 58 | 59 | \emph{\pkg{zoo} is infrastructure}. \pkg{zoo} tries to do basic things well, e.g., 60 | data reading, handling, aggregation, transformation, etc. However, it does not 61 | provide time series modeling functionality -- \pkg{zoo} rather encourages add-on 62 | packages. A list of current packages employing \pkg{zoo} can be found on the Comprehensive 63 | \proglang{R} Archive Network (CRAN) and in the \pkg{zoo} FAQ, see \code{vignette("zoo-faq", package = "zoo")}. 64 | 65 | \emph{\pkg{zoo} interfaces to all other time series packages} on CRAN (or at 66 | least all of the more popular ones and some of the relatively unknown 67 | ones as well). Thus, time series information can be passed back and forth relatively easily 68 | between `\code{zoo}' and other time series classes and hence combinations of various 69 | functionalities are facilitated. 70 | 71 | \emph{\pkg{zoo} includes extensive documentation}. In addition to the standard \code{help()} 72 | pages, \pkg{zoo} provides a set of vignettes, see \code{vignette(package = "zoo")} for a list. 73 | Furthermore, the \pkg{zoo} Development Team members also post frequently 74 | on the mailing lists (especially ``\proglang{R}-help'', ``\proglang{R}-devel'', and 75 | ``\proglang{R}-SIG-Finance'') whose archives hence contain many useful code snippets etc. 76 | 77 | \emph{\pkg{zoo} has no bug list since all bugs are fixed (almost) immediately}. Over the last 78 | years, \pkg{zoo} has grown into a mature package. Nevertheless, there are always still bugs 79 | (or border cases that are not handled well). When reported to the development team by e-mail, 80 | these typically get fixed immediately in the Subversion (SVN) repository on \proglang{R}-Forge. 81 | (As of this writing, there are a couple of entries in the \pkg{zoo} \proglang{R}-Forge bug list, 82 | however typically this is not the situation.) 83 | 84 | \emph{\pkg{zoo} includes formal regression testing}. We have started developing formal regression 85 | tests employing \proglang{R}'s own system (in \code{zoo/tests/}) as well as the \pkg{RUnit} 86 | package \citep{zoo:RUnit}. 87 | 88 | \bibliography{zoo} 89 | 90 | \end{document} 91 | -------------------------------------------------------------------------------- /vignettes/zoo-refcard-raw.tex: -------------------------------------------------------------------------------- 1 | \begin{tabular}{rp{9cm}} 2 | \multicolumn{2}{l}{\textbf{Creation}} \\ 3 | \code{zoo(x, order.by)} & creation of a \code{"zoo"} object 4 | from the observations \code{x} (a vector or a matrix) and an index 5 | \code{order.by} by which the observations are ordered. \\ 6 | & For computations on arbitrary index classes, methods to the 7 | following generic functions are assumed to work: combining \code{c()}, 8 | querying length \code{length()}, subsetting \code{[}, ordering 9 | \code{ORDER()} and value matching \code{MATCH()}. For pretty 10 | printing an \code{as.character} and/or \code{index2char} method 11 | might be helpful.\\[0.5cm] 12 | 13 | \multicolumn{2}{l}{\textbf{Creation of regular series}} \\ 14 | \code{zoo(x, order.by, freq)} & works as above but creates a \code{"zooreg"} 15 | object which inherits from \code{"zoo"} if the frequency \code{freq} complies 16 | with the index \code{order.by}. An \code{as.numeric} method has to be 17 | available for the index class.\\ 18 | \code{zooreg(x, start, end, freq)} & creates a \code{"zooreg"} series 19 | with a numeric index as above and has (almost) the same interface as 20 | \code{ts()}.\\[0.5cm] 21 | 22 | \multicolumn{2}{l}{\textbf{Standard methods}} \\ 23 | \code{plot} & plotting (alternatives: \code{xyplot} and \code{autoplot})\\ 24 | \code{lines} & adding a \code{"zoo"} series to a plot \\ 25 | \code{print} & printing \\ 26 | \code{summary} & summarizing (column-wise) \\ 27 | \code{str} & displaying structure of \code{"zoo"} objects \\ 28 | \code{head}, \code{tail} & head and tail of \code{"zoo"} objects \\[0.5cm] 29 | 30 | \multicolumn{2}{l}{\textbf{Coercion}} \\ 31 | \code{as.zoo} & coercion to \code{"zoo"} is available for objects 32 | of class \code{"ts"}, \code{"its"}, \code{"irts"} (plus a default 33 | method).\\ 34 | \code{as.}\textit{class}\code{.zoo} & coercion from \code{"zoo"} to 35 | other classes. Currently available for \textit{class} in \code{"matrix"}, 36 | \code{"vector"}, \code{"data.frame"}, \code{"list"}, \code{"irts"}, 37 | \code{"its"} and \code{"ts"}. \\ 38 | \code{is.zoo} & querying wether an object is of class \code{"zoo"} \\[0.5cm] 39 | 40 | \multicolumn{2}{l}{\textbf{Merging and binding}} \\ 41 | \code{merge} & union, intersection, left join, right join along indexes\\ 42 | \code{cbind} & column binding along the intersection of the index\\ 43 | \code{c}, \code{rbind} & combining/row binding (indexes may not overlap)\\ 44 | \code{aggregate} & compute summary statistics along a coarser grid of indexes \\[0.5cm] 45 | 46 | \multicolumn{2}{l}{\textbf{Mathematical operations}} \\ 47 | \code{Ops} & group generic functions performed along the intersection of indexes\\ 48 | \code{t} & transposing (coerces to \code{"matrix"} before) \\ 49 | \code{cumsum} & compute (columnwise) cumulative quantities: sums 50 | \code{cumsum()}, products \code{cumprod()}, maximum \code{cummax()}, 51 | minimum \code{cummin()}.\\[0.5cm] 52 | \end{tabular} 53 | 54 | \newpage 55 | 56 | \begin{tabular}{rp{9cm}} 57 | \multicolumn{2}{l}{\textbf{Extracting and replacing data and index}} \\ 58 | \code{index, time} & extract the index of a series\\ 59 | \code{index<-}, \code{time<-} & replace the index of a series\\ 60 | \code{coredata}, \code{coredata<-} & extract and replace the data associated with a \code{"zoo"} object\\ 61 | \code{lag} & lagged observations \\ 62 | \code{diff} & arithmetic and geometric differences \\ 63 | \code{start, end} & querying start and end of a series \\ 64 | \code{window, window<-} & subsetting of \code{"zoo"} objects 65 | using their index\\[0.5cm] 66 | 67 | \multicolumn{2}{l}{\textbf{\code{NA} handling}} \\ 68 | \code{na.omit} & omit \code{NA}s \\ 69 | \code{na.contiguous} & compute longest sequence of non-\code{NA} observations \\ 70 | \code{na.locf} & impute \code{NA}s by carrying forward the last observation\\ 71 | \code{na.approx} & impute \code{NA}s by interpolation\\[0.5cm] 72 | \code{na.trim} & remove leading and/or trailing \code{NA}s\\[0.5cm] 73 | 74 | \multicolumn{2}{l}{\textbf{Rolling functions}} \\ 75 | \code{rollapply} & apply a function to rolling margin of an array \\ 76 | \code{rollmean} & more efficient functions for computing the rolling mean, median 77 | and maximum are \code{rollmean()}, \code{rollmedian()} and \code{rollmax()}, respectively\\[0.5cm] 78 | 79 | \multicolumn{2}{l}{\textbf{Methods for regular series}} \\ 80 | \code{is.regular} & checks whether a series is weakly (or strictly if \code{strict = TRUE}) 81 | regular \\ 82 | \code{frequency}, \code{deltat} & extracts the frequency or its reciprocal value 83 | respectively from a series, for \code{"zoo"} series the functions try to determine 84 | the regularity and frequency in a data-driven way\\ 85 | \code{cycle} & gives the position in the cycle of a regular series \\[0.5cm] 86 | 87 | 88 | \end{tabular} 89 | -------------------------------------------------------------------------------- /vignettes/zoo-refcard.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cran/zoo/d032ed0519de3eeefe651ad9f25f7408461732a0/vignettes/zoo-refcard.pdf -------------------------------------------------------------------------------- /vignettes/zoo-refcard.tex: -------------------------------------------------------------------------------- 1 | \documentclass[notitle]{Z} 2 | \usepackage{a4wide} 3 | \begin{document} 4 | \pagestyle{empty} 5 | \centerline{\Large \bf \pkg{zoo} reference card} 6 | \vspace{0.8cm} 7 | \input{zoo-refcard-raw} 8 | \end{document} 9 | -------------------------------------------------------------------------------- /vignettes/zoo.bib: -------------------------------------------------------------------------------- 1 | @Article{zoo:Zeileis+Grothendieck:2005, 2 | author = {Achim Zeileis and Gabor Grothendieck}, 3 | title = {\pkg{zoo}: \proglang{S3} Infrastructure for Regular and Irregular Time Series}, 4 | journal = {Journal of Statistical Software}, 5 | year = 2005, 6 | volume = 14, 7 | number = 6, 8 | pages = {1--27}, 9 | url = {10.18637/jss.v014.i06} 10 | } 11 | 12 | @Manual{zoo:R:2008, 13 | title = {\proglang{R}: {A} Language and Environment for Statistical Computing}, 14 | author = {{\proglang{R} Core Team}}, 15 | organization = {\proglang{R} Foundation for Statistical Computing}, 16 | address = {Vienna, Austria}, 17 | year = {2017}, 18 | url = {https://www.R-project.org/} 19 | } 20 | 21 | @Article{zoo:Zeileis+Leisch+Hornik:2002, 22 | author = {Achim Zeileis and Friedrich Leisch and Kurt Hornik and 23 | Christian Kleiber}, 24 | title = {\pkg{strucchange}: {A}n \proglang{R} Package for Testing 25 | for Structural Change in Linear Regression Models}, 26 | journal = {Journal of Statistical Software}, 27 | year = 2002, 28 | volume = 7, 29 | number = 2, 30 | pages = {1--38}, 31 | url = {10.18637/jss.v007.i02} 32 | } 33 | 34 | @Article{zoo:Zeileis:2005, 35 | author = {Achim Zeileis}, 36 | title = {Implementing a Class of Structural Change Tests: An Econometric Computing Approach}, 37 | journal = {Computational Statistics \& Data Analysis}, 38 | volume = {50}, 39 | issue = {11}, 40 | pages = {2987--3008}, 41 | year = {2006}, 42 | doi = {10.1016/j.csda.2005.07.001}, 43 | } 44 | 45 | @Article{zoo:Zeileis+Hothorn+Hornik:2008, 46 | author = {Achim Zeileis and Torsten Hothorn and Kurt Hornik}, 47 | title = {Model-Based Recursive Partitioning}, 48 | journal = {Journal of Computational and Graphical Statistics}, 49 | year = {2008}, 50 | volume = {17}, 51 | number = {2}, 52 | pages = {492--514}, 53 | doi = {10.1198/106186008X319331} 54 | } 55 | 56 | @Book{zoo:Kleiber+Zeileis:2008, 57 | title = {Applied Econometrics with \proglang{R}}, 58 | author = {Christian Kleiber and Achim Zeileis}, 59 | year = {2008}, 60 | publisher = {Springer-Verlag}, 61 | address = {New York}, 62 | doi = {10.1007/978-0-387-77318-6}, 63 | url = {http://CRAN.R-project.org/package=AER}, 64 | } 65 | 66 | @Manual{zoo:Rmetrics:2008, 67 | title = {\pkg{Rmetrics}: {A}n Environment and Software Collection for 68 | Teaching Financial Engineering and Computational Finance}, 69 | author = {Diethelm Wuertz}, 70 | year = {2016}, 71 | note = {\proglang{R}~packages \pkg{fArma}, \pkg{fAsianOptions}, 72 | \pkg{fAssets}, \pkg{fBasics}, \pkg{fCalendar}, \pkg{fCopulae}, 73 | \pkg{fEcofin}, \pkg{fExoticOptions}, \pkg{fExtremes}, \pkg{fGarch}, 74 | \pkg{fImport}, \pkg{fMultivar}, \pkg{fNonlinear}, \pkg{fOptions}, 75 | \pkg{fPortfolio}, \pkg{fRegression}, \pkg{fSeries}, \pkg{fTrading}, 76 | \pkg{fUnitRoots}, \pkg{fUtilities}}, 77 | url = {http://www.Rmetrics.org/}, 78 | } 79 | 80 | @Manual{zoo:tseries:2007, 81 | title = {\pkg{tseries}: Time Series Analysis and Computational Finance}, 82 | author = {Adrian Trapletti and Kurt Hornik}, 83 | year = {2017}, 84 | note = {\proglang{R}~package version~0.10-38}, 85 | url = {https://CRAN.R-project.org/package=tseries} 86 | } 87 | 88 | @Manual{zoo:its:2004, 89 | title = {\pkg{its}: Irregular Time Series}, 90 | author = {Giles Heywood}, 91 | organization = {Portfolio \& Risk Advisory Group and Commerzbank Securities}, 92 | year = {2009}, 93 | note = {\proglang{R} package version 1.1.8}, 94 | url = {https://CRAN.R-project.org/src/contrib/Archive/its/}, 95 | } 96 | 97 | @Manual{zoo:DAAG:2004, 98 | title = {\pkg{DAAG}: Data Analysis and Graphics}, 99 | author = {John Maindonald and W. John Braun}, 100 | year = {2015}, 101 | note = {\proglang{R} package version 1.22}, 102 | url = {https://CRAN.R-project.org/package=DAAG}, 103 | } 104 | 105 | @Manual{zoo:xts:2008, 106 | title = {\pkg{xts}: Extensible Time Series}, 107 | author = {Jeffrey A. Ryan and Josh M. Ulrich}, 108 | year = {2014}, 109 | note = {\proglang{R} package version 0.9-7}, 110 | url = {https://CRAN.R-project.org/package=xts}, 111 | } 112 | 113 | @Manual{zoo:RUnit, 114 | title = {\pkg{RUnit}: \proglang{R} Unit Test Framework}, 115 | author = {Matthias Burger and Klaus J\"unemann and Thomas K\"onig}, 116 | year = {2015}, 117 | note = {\proglang{R} package version 0.4.31}, 118 | url = {https://CRAN.R-project.org/package=RUnit}, 119 | } 120 | 121 | @Book{lattice, 122 | title = {\pkg{lattice}: Multivariate Data Visualization with \proglang{R}}, 123 | author = {Deepayan Sarkar}, 124 | publisher = {Springer-Verlag}, 125 | address = {New York}, 126 | year = {2008}, 127 | } 128 | 129 | @Book{ggplot2, 130 | author = {Hadley Wickham}, 131 | title = {\pkg{ggplot2}: Elegant Graphics for Data Analysis}, 132 | publisher = {Springer-Verlag}, 133 | address = {New York}, 134 | year = 2009, 135 | } 136 | 137 | --------------------------------------------------------------------------------