有人能解释我在这里做错了什么吗:
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
我预计手段是:
1 1
2 2
3 3
相反,平均值似乎是全局平均值(第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
此外,在group_by
中使用列名更为常见:
> temp %>% group_by(b) %>% summarise(n=n(), mean=mean(b, na.rm=T))
# A tibble: 3 × 3
b n mean
<dbl> <int> <dbl>
1 1 3 1
2 2 3 2
3 3 3 3
另一种方法是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
始终记得在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))