英文:
Estimating quantile correlations with rolling window
问题
我想估计两个变量之间的分位数相关性,比如Y和X,使用滚动窗口。我正在使用R包QCSIS
来实现这个目的。我尝试执行以下代码:
library(QCSIS)
# 生成一些随机变量
n <- 4000
x <- rnorm(n)
y <- 2 * x + rt(n, df = 1)
tau <- 9 / 10
# 计算静态分位数相关性
fit <- qc(x = x, y = y, tau = tau)
fit$rho
# 计算滚动窗口分位数相关性
s <- 260 # 窗口大小
Rho.mat <- matrix(0, 1, (n - s + 1)) # 创建空矩阵以存储相关系数
# 执行循环
for (i in 1:(n - s + 1)) {
fit <- qc(x = x, y = y, tau = tau)
Rho.mat[,i] <- fit$rho
}
然而,这段代码并不会为每个窗口提供分位数相关性,而只会重复静态分位数相关性!我在网上找到的大多数其他解决方案都与线性回归有关,与我正在使用的函数不符。这就是为什么我使用循环的原因。
英文:
I would like to estimate the quantile correlations between two variables, say Y and X, using the rolling window. I am using the R package QCSIS
for this purpose. I tried to do the following
library(QCSIS)
#Generate some random variables
n <- 4000
x <- rnorm(n)
y <- 2 * x + rt(n,df = 1)
tau <- 9 / 10
#calculate the static quantile correlation
fit<-qc(x = x, y = y, tau = tau)
fit$rho
#calculate the rolling window quantile correlations
s<-260 #The window size
Rho.mat <- matrix(0,1,(n-s+1)) #create empty matrix to store the correlation coefficients
#running the loop
for(i in 1:(n-s+1)) {
fit <- qc(x = x, y = y, tau = tau)
Rho.mat[,i] <- fit$rho
}
However, this code does not give the quantile correlation for each window and only repeats the static quantile correlation! Most of the other solutions I found online are related to linear regression and do not fit with the function I am using. That is why I am using a loop.
答案1
得分: 2
使用rollapplyr
如下所示,以避免循环:
library(zoo)
rollapplyr(cbind(x, y), s, function(z) qc(z[, 1], z[, 2], tau)$rho,
fill = NA, by.column = FALSE)
或者通过索引:
rollapplyr(seq_along(x), s, function(ix) qc(x[ix], y[ix], tau)$rho, fill = NA)
我们可以像这样检查结果:
library(zoo)
r.roll <- rollapplyr(cbind(x, y), s, function(z) qc(z[, 1], z[, 2], tau)$rho,
fill = NA, by.column = FALSE)
r.for <- x
for(i in seq_along(r.for)) {
r.for[i] <- if (i < s) NA else {
ix <- seq(to = i, length = s)
qc(x[ix], y[ix], tau = tau)$rho
}
}
identical(r.roll, r.for)
## [1] TRUE
英文:
Use rollapplyr as follows to avoid loops:
library(zoo)
rollapplyr(cbind(x, y), s, function(z) qc(z[, 1], z[, 2], tau)$rho,
fill = NA, by.column = FALSE)
or over the indexes:
rollapplyr(seq_along(x), s, function(ix) qc(x[ix], y[ix], tau)$rho, fill = NA)
We can check the result like this:
library(zoo)
r.roll <- rollapplyr(cbind(x, y), s, function(z) qc(z[, 1], z[, 2], tau)$rho,
fill = NA, by.column = FALSE)
r.for <- x
for(i in seq_along(r.for)) {
r.for[i] <- if (i < s) NA else {
ix <- seq(to = i, length = s)
qc(x[ix], y[ix], tau = tau)$rho
}
}
identical(r.roll, r.for)
## [1] TRUE
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论