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

使用dplyr的group_by与summarise分组求均值失败问题求助

分组计算均值未按预期分组问题

我不清楚操作哪里出错,数据集构建代码如下:

install.packages("random")              
library("random")


df <- data.frame(V1 = randomNumbers(n = 18,min = 1,max = 20, col=1),
                 factor_col = c(rep("A", 18)),
                 mouse_ID = c(1:18))

df2 <- data.frame(V1 = randomNumbers(n = 14,min = 1,max = 20, col=1),
                  factor_col = c(rep("B", 14)),
                  mouse_ID = c(1:14))

df3 <- data.frame(V1 = randomNumbers(n = 13,min = 1,max = 20, col=1),
                  factor_col = c(rep("C", 13)),
                  mouse_ID = c(6:18))

Table = bind_rows(df, df2)
Table = bind_rows(Table, df3)

Table$mouse_ID = as.factor(Table$mouse_ID)
Table$factor_col = as.factor(Table$factor_col)

我想要按mouse_ID分组计算V1的均值,执行代码:

Table2 = Table %>%
  group_by(mouse_ID) %>%
  summarise(mean_V1 = mean(V1, na.rm = TRUE))

但仅得到一个V1均值,未按mouse_ID分组。请问是因为各mouse_ID出现频率不一致导致的吗?


问题原因

不是mouse_ID出现频率的问题,核心原因是未加载dplyr包。你用到的bind_rows、%>%管道符、group_by、summarise都是dplyr包中的函数,但你的代码只加载了random包,没有加载dplyr,导致R无法正确识别这些分组相关函数,最终默认计算了整个数据集的均值。

解决方法

在代码开头添加dplyr包的安装与加载代码(如果未安装过的话):

# 若未安装dplyr则先安装
if (!require(dplyr)) {
  install.packages("dplyr")
  library(dplyr)
}

或者直接简化为:

install.packages("dplyr")
library(dplyr)

加载dplyr后再重新执行你的分组计算代码,就能按mouse_ID分组得到每个ID对应的V1均值了。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 02:17:23