index.RdGeneric functions for extracting the index of an object and replacing it.
index(x, ...)
index(x) <- valueindex is a generic function for extracting the index
of objects, currently it has a default method and a method
for zoo objects which is the same as the
time method for zoo objects.
Another pair of generic functions provides replacing
the index or time attribute.
Methods are available for "zoo" objects only, see examples below.
The start and end of the index/time can be queried by using
the methods of start and end.
suppressWarnings(RNGversion("3.5.0"))
set.seed(1)
x.date <- as.Date(paste(2003, 2, c(1, 3, 7, 9, 14), sep = "-"))
x <- zoo(rnorm(5), x.date)
## query index/time of a zoo object
index(x)
#> [1] "2003-02-01" "2003-02-03" "2003-02-07" "2003-02-09" "2003-02-14"
time(x)
#> [1] "2003-02-01" "2003-02-03" "2003-02-07" "2003-02-09" "2003-02-14"
## change class of index from Date to POSIXct
## relative to current time zone
x
#> 2003-02-01 2003-02-03 2003-02-07 2003-02-09 2003-02-14
#> -0.6264538 0.1836433 -0.8356286 1.5952808 0.3295078
index(x) <- as.POSIXct(format(time(x)),tz="")
x
#> 2003-02-01 2003-02-03 2003-02-07 2003-02-09 2003-02-14
#> -0.6264538 0.1836433 -0.8356286 1.5952808 0.3295078
## replace index/time of a zoo object
index(x) <- 1:5
x
#> 1 2 3 4 5
#> -0.6264538 0.1836433 -0.8356286 1.5952808 0.3295078
time(x) <- 6:10
x
#> 6 7 8 9 10
#> -0.6264538 0.1836433 -0.8356286 1.5952808 0.3295078
## query start and end of a zoo object
start(x)
#> [1] 6
end(x)
#> [1] 10
## query index of a usual matrix
xm <- matrix(rnorm(10), ncol = 2)
index(xm)
#> [1] 1 2 3 4 5