-
Notifications
You must be signed in to change notification settings - Fork 0
/
window.piar_index.R
53 lines (50 loc) · 1.43 KB
/
window.piar_index.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#' Get the indexes for a window of time periods
#' @noRd
index_window <- function(x, start, end) {
if (is.null(start)) start <- start(x)
if (is.null(end)) end <- end(x)
start <- match_time(as.character(start), x$time)
end <- match_time(as.character(end), x$time)
if (start > end) {
stop("'start' must refer to a time period before 'end'")
}
seq.int(start, end)
}
#' Index window
#'
#' Extract and replace index values over a window of time periods.
#'
#' @param x A price index, as made by, e.g., [elemental_index()].
#' @param start The time period to start the window. The default in the first
#' period of `x`.
#' @param end The time period to end the window. The default is the last period
#' of `x`.
#' @param ... Not currently used.
#' @param value A numeric vector or price index.
#'
#' @returns
#' `window()` extracts a price index over a window of time periods that
#' inherits from the same class as `x`. The replacement method replaces these
#' with `value`.
#'
#' @examples
#' x <- as_index(matrix(1:9, 3))
#'
#' window(x, "2")
#'
#' window(x, "2") <- 1
#' x
#'
#' @family index methods
#' @importFrom stats window
#' @export
window.piar_index <- function(x, start = NULL, end = NULL, ...) {
x[, index_window(x, start, end)]
}
#' @rdname window.piar_index
#' @importFrom stats window<-
#' @export
`window<-.piar_index` <- function(x, start = NULL, end = NULL, ..., value) {
x[, index_window(x, start, end)] <- value
x
}