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

R语言cor()函数报错‘AgeGroup_30_to_34未找到’求助

问题原因

报错的核心是管道中cor()的调用方式错误:

  • 管道最后传递给cor()的是过滤后的完整数据集(数据框),但你写的cor(Sunshine_in_hours, AgeGroup_30_to_34)会把Sunshine_in_hours作为cor()的第一个参数x,然后R会去全局环境寻找AgeGroup_30_to_34这个独立对象,而非数据框中的列,因此触发找不到对象的错误。
解决方案

提供三种可行的修改方式,任选其一即可:

方式1:用dplyr::summarize()计算(推荐,符合管道风格)

将最后一步的cor()替换为summarize(),在summarize()内部可以直接引用数据框的列:

Combined <- inner_join(covidS, weatherS, by = 'Date')%>%
  mutate(Date = mdy(Date),
         Year = year(Date),
         Month = month(Date),
         Day = day(Date))%>%
  select(Date, Year, Month, AgeGroup_30_to_34, Sunshine_in_hours, City)%>%
  filter(City == 'Melbourne')%>%
  summarize(correlation = cor(Sunshine_in_hours, AgeGroup_30_to_34, use = "complete.obs"))
  • 加上use = "complete.obs"是为了自动忽略缺失值,避免因缺失值导致的额外报错。

方式2:用with()包裹cor()

利用with()在数据框的环境中查找变量,适配管道传递的数据框:

Combined <- inner_join(covidS, weatherS, by = 'Date')%>%
  mutate(Date = mdy(Date),
         Year = year(Date),
         Month = month(Date),
         Day = day(Date))%>%
  select(Date, Year, Month, AgeGroup_30_to_34, Sunshine_in_hours, City)%>%
  filter(City == 'Melbourne')%>%
  with(cor(Sunshine_in_hours, AgeGroup_30_to_34, use = "complete.obs"))

方式3:拆分管道,单独计算相关性

先完成数据预处理并赋值给Combined,再单独调用cor():

Combined <- inner_join(covidS, weatherS, by = 'Date')%>%
  mutate(Date = mdy(Date),
         Year = year(Date),
         Month = month(Date),
         Day = day(Date))%>%
  select(Date, Year, Month, AgeGroup_30_to_34, Sunshine_in_hours, City)%>%
  filter(City == 'Melbourne')

# 单独计算相关性
correlation <- cor(Combined$Sunshine_in_hours, Combined$AgeGroup_30_to_34, use = "complete.obs")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 20:30:50