You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

使用R语言group_by和summarise时出现"Object not found"错误求助

解决dplyr summarise时"object not found"的问题

我碰到过类似的情况,结合你的代码和排查过程,给你几个针对性的解决方案:

1. 强制指定dplyr命名空间,避免函数冲突

你同时加载了tidyverse和单独的dplyr,再加上operators包,很可能出现函数命名冲突。试试在summarise前加上dplyr::前缀,明确调用dplyr的函数:

temp2 <- temp1 %>% 
  select(state, race, for_count) %>% 
  group_by(state, race) %>% 
  dplyr::summarise(num_shootings = sum(for_count))

2. 排查operators包的干扰

operators包经常会重定义一些常用操作符或函数,和dplyr的语法产生冲突。先卸载并移除这个包再测试:

detach("package:operators", unload = TRUE)

之后重新运行你的代码,看是否能正常执行。

3. 分步执行代码定位问题

把管道拆成分步操作,逐一排查每一步的输出:

# 第一步:确认select后的结果包含for_count
temp_select <- temp1 %>% select(state, race, for_count)
print(temp_select)

# 第二步:确认分组对象结构正常
temp_grouped <- temp_select %>% group_by(state, race)
str(temp_grouped)

# 第三步:单独执行summarise
temp2 <- temp_grouped %>% summarise(num_shootings = sum(for_count))

这样能快速定位问题出在哪个环节。

4. 用基础R函数验证数据

aggregate函数做替代测试,确认数据本身没有问题:

aggregate(for_count ~ state + race, data = temp1, sum)

如果这个能正常输出预期结果,那基本可以确定是dplyr相关的命名空间冲突问题,用第一种方法就能解决。

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

火山引擎 最新活动