You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从R语言的ccf函数推断信息并计算全滞后相关指标

问题:从R语言ccf函数生成全滞后项的r、ax、ay表格

给定以下数据,需要计算Spend和Income在正负15个滞后项的互相关系数r,以及对应滞后项的Spend自相关系数ax、Income自相关系数ay,并生成完整表格:

Spend <- c(5, 3, 6, 5, 8, 9, 10, 17, 12, 11, 10, 9)
Income <- c(25, 29, 22, 34, 22, 28, 29, 31, 34, 45, 45, 40)
ccf(Spend, Income, lag.max = 15)

已知滞后0的结果为:

cor(Spend,Income)  # 结果:0.34
as.numeric(acf(Spend,plot=F)[[1]][2])  # ax(lag1):0.62
as.numeric(acf(Income,plot=F)[[1]][2]) # ay(lag1):0.52

需要生成包含所有±15滞后项的表格,格式如下:

r         ax          ay
lag0    0.34011   0.6283999   0.52305
lag1
lag-1
...
lag15
lag-15

解决方案

步骤1:获取ccf的完整结果

调用ccf并保存结果,关闭绘图以直接获取数值:

# 定义数据
Spend <- c(5, 3, 6, 5, 8, 9, 10, 17, 12, 11, 10, 9)
Income <- c(25, 29, 22, 34, 22, 28, 29, 31, 34, 45, 45, 40)

# 计算互相关,保存结果(不绘图)
ccf_result <- ccf(Spend, Income, lag.max = 15, plot = FALSE)

步骤2:提取滞后项和互相关系数r

从ccf_result中提取所有滞后项(从-15到15)和对应的互相关系数:

# 提取所有滞后项
lags <- ccf_result$lag
# 提取互相关系数r(ccf返回三维数组,取第一维度转为一维)
r_vals <- ccf_result$acf[, , 1]

步骤3:计算对应滞后项的自相关系数ax和ay

自相关函数acf默认返回非负滞后的结果,而负滞后的自相关与正滞后值相等(自相关是偶函数),因此可以通过取滞后绝对值来匹配:

# 计算Spend的自相关(0到15滞后)
acf_spend <- acf(Spend, lag.max = 15, plot = FALSE)
# 生成所有±滞后对应的ax值
ax_vals <- sapply(lags, function(k) {
  if (k == 0) acf_spend$acf[acf_spend$lag == 0]
  else acf_spend$acf[acf_spend$lag == abs(k)]
})

# 同理计算Income的自相关ay值
acf_income <- acf(Income, lag.max = 15, plot = FALSE)
ay_vals <- sapply(lags, function(k) {
  if (k == 0) acf_income$acf[acf_income$lag == 0]
  else acf_income$acf[acf_income$lag == abs(k)]
})

步骤4:合并并整理表格

将数据合并为数据框,调整格式以符合需求:

# 合并数据
result_table <- data.frame(
  r = round(r_vals, 5),
  ax = round(ax_vals, 5),
  ay = round(ay_vals, 5)
)

# 设置行名为"lagX"格式,按滞后项排序
rownames(result_table) <- paste0("lag", lags)
result_table <- result_table[order(lags), ]

# 打印最终表格
print(result_table)

内容的提问来源于stack exchange,提问作者temor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 05:59:56