-
Notifications
You must be signed in to change notification settings - Fork 0
/
acfs.R
213 lines (187 loc) · 5.9 KB
/
acfs.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
#' Calculate regime-switching auto-correlation
#'
#' @param x A univariate numeric time series.
#' @param label A factor of regime labels.
#' @param lag_max Maximum lag at which to calculate the acf.
#' @param demean Logical. Should the covariances be about the sample means?
#'
#' @return Mean auto-correlations for each group in `label`.
#' @export
#' @examples
#' set.seed(123)
#' x <- rnorm(100)
#' label <- sample(1:2, 100, replace = TRUE)
#' acf_rs(x, label = factor(label), lag_max = 3)
acf_rs <- function(x, label, lag_max, demean = TRUE) {
stopifnot(length(x) == length(label))
if (demean) {
x <- x - mean(x)
}
n_reg <- length(unique(label))
n_x <- length(x)
lvs <- levels(label)
lag_max <- ifelse(lag_max >= n_x, n_x - 1, lag_max)
x <- stats::ts(x)
acf_ls <- lapply(1:n_reg, function(x) {
x <- numeric(lag_max + 1)
x
})
for (u in 0:lag_max) {
x_u <- stats::lag(x, -u)
x_x_u <- (x * x_u)
label_u <- label[(1 + u):n_x]
for (k in 1:n_reg) {
numer <- x_x_u[label_u == lvs[k]]
if (length(numer) == 0) {
acf_ls[[k]][u + 1] <- NA
} else {
acf_ls[[k]][u + 1] <- sum(numer)
}
}
}
acf_ls <- lapply(acf_ls, function(x) x / x[1])
acf_ls <- lapply(acf_ls, function(x) {
names(x) <- paste0("lag", 0:lag_max)
x
})
names(acf_ls) <- paste0("Regime ", lvs)
return(acf_ls)
}
#' Generic function for calculating autocorrelation
#'
#' @param x An **R** object.
#' @param ... Additional parameters or attributes.
#'
#' @return A vector of mean auto-correlations for `mcgf` objects, or that plus
#' a list of regime-switching mean auto-correlations for `mcgf_rs` objects.
#'
#' @details
#' Refer to [`acfs.mcgf()`] and [`acfs.mcgf_rs()`] for more details.
#'
#' @export
acfs <- function(x, ...) {
UseMethod("acfs")
}
#' Extract, calculate, or assign mean auto-correlations for an `mcgf` or
#' `mcgf_rs` object
#'
#' @name acfs.mcgf
#'
#' @param x An `mcgf` or `mcgf_rs` object.
#' @param lag_max Maximum lag at which to calculate the acf.
#' @param replace Logical; if TRUE, `acfs` are recalculated.
#' @param ... Additional parameters or attributes.
#'
#' @return [`acfs()`] returns (regime-switching) mean auto-correlations.
#' [`add_acfs()`] returns the same object with additional attributes of
#' (regime-switching) mean auto-correlations.
#' @export
#'
#' @details
#'
#' For `mcgf` objects, [`acfs()`] computes mean auto-correlations for each time
#' lag across locations. The output is a vector of acfs.
#'
#' For `mcgf_rs` objects, [`acfs()`] computes regime-switching mean
#' auto-correlations for each time lag across locations. The output is a list of
#' vectors of acfs, where each vector in the list corresponds to the acfs for
#' a regime.
#'
#' [`acfs<-`] assigns `acfs` to `x`.
#'
#' [`add_acfs()`] adds `acfs` to `x`.
#'
#' @examples
#' # Calculate acfs for 'sim1'
#' data(sim1)
#' sim1_mcgf <- mcgf(sim1$data, dists = sim1$dists)
#' acfs(sim1_mcgf, lag_max = 5)
#'
#' # Add acfs to 'sim1_mcgf'
#' sim1_mcgf <- add_acfs(sim1_mcgf, lag_max = 5)
#' print(sim1_mcgf, "acfs")
#'
#' # Calculate acfs for 'sim2'
#' data(sim2)
#' sim2_mcgf <- mcgf_rs(sim2$data, dists = sim2$dists, label = sim2$label)
#' acfs(sim2_mcgf, lag_max = 5)
#'
#' # Add acfs to 'sim2_mcgf'
#' sim2_mcgf <- add_acfs(sim2_mcgf, lag_max = 5)
#' print(sim2_mcgf, "acfs")
#' @family functions related to calculating acfs and ccfs
acfs.mcgf <- function(x, lag_max, replace = FALSE, ...) {
acfs <- attr(x, "acfs", exact = TRUE)
if (!is.null(acfs) && !replace) {
return(acfs)
} else {
ccfs <- attr(x, "ccfs", exact = TRUE)
if (!is.null(ccfs) && !is.mcgf_rs(x) && dim(ccfs)[3] != lag_max + 1) {
warning("`lag_max` must be the same as that in `ccfs`")
}
if (!is_numeric_scalar(lag_max)) {
stop("`lag_max` must be numeric.", call. = FALSE)
}
if (lag_max < 0) {
stop("`lag_max` must be a positive integer.", call. = FALSE)
}
data <- x
n_var <- ncol(data)
acf_data <- matrix(NA, nrow = lag_max + 1, ncol = n_var)
for (i in 1:n_var) {
acf_data[, i] <- stats::acf(data[, i],
lag.max = lag_max,
plot = FALSE, ...
)$acf
}
acfs <- rowMeans(acf_data)
names(acfs) <- paste0("lag", 0:lag_max)
return(acfs)
}
}
#' @rdname acfs.mcgf
#' @export
acfs.mcgf_rs <- function(x, lag_max, replace = FALSE, ...) {
acfs <- attr(x, "acfs", exact = TRUE)
if (!is.null(acfs) && !replace) {
return(acfs)
} else {
label <- attr(x, "label", exact = TRUE)
ccfs <- attr(x, "ccfs", exact = TRUE)
if (!is.null(ccfs) && dim(ccfs$ccfs)[3] != lag_max + 1) {
warning("`lag_max` must be the same as that in `ccfs`")
}
if (!is_numeric_scalar(lag_max)) {
stop("`lag_max` must be numeric.", call. = FALSE)
}
if (lag_max < 0) {
stop("`lag_max` must be a positive integer.", call. = FALSE)
}
data <- x
n_var <- ncol(data)
acf_data <- list()
acf_data <- acf_rs(data[, 1], label = label, lag_max = lag_max)
for (i in 2:n_var) {
z <- acf_rs(data[, i], label = label, lag_max = lag_max)
acf_data <- Map(cbind, acf_data, z)
}
acfs_rs <- lapply(acf_data, rowMeans)
acfs <- acfs.mcgf(x, lag_max = lag_max)
return(list(acfs = acfs, acfs_rs = acfs_rs))
}
}
#' @rdname acfs.mcgf
#' @param value A Vector of mean of auto-correlations for time lags starting
#' from 0.
#' @export
`acfs<-` <- function(x, value) {
attr(x, "acfs") <- value
return(x)
}
#' @rdname acfs.mcgf
#' @export
add_acfs <- function(x, lag_max, ...) {
acfs <- acfs(x = x, lag_max = lag_max, ...)
attr(x, "acfs") <- acfs
return(x)
}