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

如何用R计算不同国家电价在周度/月度维度的相关系数

问题原因分析
  • 第一种xts方案错误:apply.monthly/apply.weekly传入的计算函数需要基于每个时间周期的切片数据运算,你直接使用全量数据集SEE_prices$GR/SEE_prices$SR,每次计算的都是全量数据的相关系数,不符合分组计算的要求。
  • 第二种dplyr方案错误:summarise中调用了prices_df$GR/prices_df$SR,这是直接读取全量数据集的列,不会受group_by分组规则限制,因此所有分组的计算结果都和全量相关系数一致。
正确实现方案

方案1:tidyverse(更易读,推荐)

library(lubridate)
library(dplyr)

# 预处理时间列
prices_df <- prices_df %>% 
  mutate(DATETIME = ymd_hms(DATETIME))

# 周度相关系数计算
week_cor <- prices_df %>% 
  group_by(year = year(DATETIME), week = isoweek(DATETIME)) %>% 
  summarise(
    date_count = n_distinct(date(DATETIME)),
    gr_sr_cor = cor(GR, SR, use = "complete.obs"), # 直接用列名会自动取分组内数据,参数设置自动跳过缺失值
    .groups = "drop"
  )

# 月度相关系数计算
month_cor <- prices_df %>% 
  group_by(year = year(DATETIME), month = month(DATETIME)) %>% 
  summarise(
    date_count = n_distinct(date(DATETIME)),
    gr_sr_cor = cor(GR, SR, use = "complete.obs"),
    .groups = "drop"
  )

如果需要计算所有国家两两的相关系数,可以将数据转为长格式后分组运算,或者配合corrr包的相关函数扩展即可。

方案2:xts实现

library(xts)
# 构造xts对象时要排除DATETIME列,避免非数值字段进入矩阵
SEE_prices <- xts(x = prices_df[,setdiff(colnames(prices_df), "DATETIME")], 
                  order.by = prices_df$DATETIME)
storage.mode(SEE_prices) <- "numeric"
SEE_prices <- na.locf(SEE_prices)

# 周度相关系数:传入匿名函数,x代表每个周的切片数据
week_cor_xts <- apply.weekly(SEE_prices, function(x) cor(x[,"GR"], x[,"SR"], use = "complete.obs"))
# 月度相关系数
month_cor_xts <- apply.monthly(SEE_prices, function(x) cor(x[,"GR"], x[,"SR"], use = "complete.obs"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 17:06:03