dplyr返回每个组的全局平均值,而不是每个组的平均值
有人能解释一下我做错了什么吗:dplyr返回每个组的全局平均值,而不是每个组的平均值,r,dplyr,R,Dplyr,有人能解释一下我做错了什么吗: library(dplyr) temp<-data.frame(a=c(1,2,3,1,2,3,1,2,3),b=c(1,2,3,1,2,3,1,2,3)) temp%>%group_by(temp[,1])%>%summarise(n=n(),mean=mean(temp[,2],na.rm=T)) # A tibble: 3 × 3 `temp[, 1]` n mean <dbl> <int&
library(dplyr)
temp<-data.frame(a=c(1,2,3,1,2,3,1,2,3),b=c(1,2,3,1,2,3,1,2,3))
temp%>%group_by(temp[,1])%>%summarise(n=n(),mean=mean(temp[,2],na.rm=T))
# A tibble: 3 × 3
`temp[, 1]` n mean
<dbl> <int> <dbl>
1 1 3 2
2 2 3 2
3 3 3 2
相反,平均值似乎是全局平均值(第2列中的所有值除以实例数)=18/9=2
我怎样才能得到我期望的结果呢 您的问题是您计算的是
temp[,2]
的平均值,而不是组中的列(mean(temp[,2],na.rm=T)
完全不依赖于上下文)。您需要执行以下操作:
> temp %>% group_by(temp[,1]) %>% summarise(n=n(), mean=mean(b, na.rm=T))
# A tibble: 3 × 3
`temp[, 1]` n mean
<dbl> <int> <dbl>
1 1 3 1
2 2 3 2
3 3 3 3
始终记住在
dplyr
中使用列名。当您尝试按列的索引而不是名称引用列时,会遇到类似的问题。所以你用的不是代码
temp%>%group_by(temp[,1])%>%summarise(n=n(),mean=mean(temp[,2],na.rm=T))
试试下面这个。给出了预期的结果
temp%>%group_by(b)%>%summarise(n=n(),mean=mean(b))
另一种方法是
data.table
library(data.table)
setDT(temp)[, .(n = .N, mean = mean(b)), by = a]
# a n mean
#1: 1 3 1
#2: 2 3 2
#3: 3 3 3
我可能也会避免在
组中使用索引。
temp%>%group_by(b)%>%summarise(n=n(),mean=mean(b))
library(data.table)
setDT(temp)[, .(n = .N, mean = mean(b)), by = a]
# a n mean
#1: 1 3 1
#2: 2 3 2
#3: 3 3 3