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
相关产品推荐
相关产品推荐

