[英]Partial Cross-correlation in R
我認為標題是不言自明的。 我想計算為其他滯后值控制的兩個時間序列之間的互相關。 我找不到任何現有的 R 代碼來執行此操作,而且我對自己的統計學(或 R)知識完全沒有信心嘗試自己編寫一些東西。 它類似於偏自相關函數,只是為了互相關而不是自相關。
如果它有幫助的話,我更大的目標是尋找物理系統的不同測量之間的滯后相關性(首先,來自耀變體伽馬射線測量的通量和光子指數),目的是建立一個通用的線性模型來嘗試預測燃燒事件。
看看我的回答我自己的問題(與您發布的一個)。
您可以使用 R 中的pacf
函數,將其擴展為具有 2 個或更多時間序列的矩陣。 我檢查了多元acf
和ccf
函數之間的結果,它們產生相同的結果,因此可以得出關於多元pacf
和不存在的pccf
的相同結論。
我相信這項工作,
pccf <- function(x,y,nlags=7,partial=TRUE){
# x (numeric): variable that leads y
# y (numeric): variable of interest
# nlags (integer): number of lags (uncluding zero)
# partial (boolean): partial or absolute correlation
# trim y
y <- y[-(1:(nlags-1))]
# lagged matrix of x
x_lagged <- embed(x,nlags)
# process for each lag
rho <- lag <- NULL
for(i in 1:(nlags)){
if(partial){
# residuals of x at lag of interest regressed on all other lags of x
ex <- lm(x_lagged[,i] ~ x_lagged[,-i])$residuals
# residuals of y regressed on all lags of x but the one of interest
ey <- lm(y ~ x_lagged[,-i])$residuals
}else{
ex <- x_lagged[,i]
ey <- y
}
# calculate correlation
rho[i] = cor(ex,ey, use="pairwise.complete.obs")
lag[i] = i-1
}
return(
tibble(lag=lag, rho=rho) %>%
arrange(lag)
)
}
# test
n <- 200 # count
nlag <- 6 # number of lags
x <- as.numeric(arima.sim(n=n,list(ar=c(phi=0.9)),sd=1)) # simulate times series x
y <- lag(x,nlag) + rnorm(n,0,0.5) # simulate y to lag x
y <- y[(nlag+1):n] # remove NAs from lag
x <- x[(nlag+1):n] # align with y
pccf(x,y,nlags=10,partial=FALSE) %>%
mutate(type='Cross correlation') %>%
bind_rows(
pccf(x,y,nlags=10,partial=TRUE) %>%
mutate(type='Partial cross correlation')
) %>%
ggplot() +
geom_col(aes(-lag,rho),width=0.1) +
facet_wrap(~type,scales='free_y', ncol=1) +
scale_x_continuous(breaks=-10:0) +
theme_bw(base_size=20)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.