dplyr:即使没有选择它,也可以获取group_by-column [英] dplyr: getting group_by-column even when not selecting it
问题描述
当选择列时,我得到一列我没有选择,但它是一个group_by列:
When selecting columns I get one column I haven't selected but it's a group_by column:
library(magrittr)
library(dplyr)
df <- data.frame(i=c(1,1,1,1,2,2,2,2), j=c(1,2,1,2,1,2,1,2), x=runif(8))
df %>%
group_by(i,j) %>%
summarize(s=sum(x)) %>%
filter(i==1) %>%
select(s)
我得到列,即使我没有选择它:
I get column i even I haven't selected it:
i s
1 1 0.8355195
2 1 0.9322474
为什么这发生了(为什么不列j?),我该如何避免呢?好的,我可以在开始时过滤....
Why does this happen (why not column j?) and how can I avoid it? Okay I could filter at the beginning....
推荐答案
这是因为默认情况下继承了分组变量。请参阅 dplyr
小插曲:
That's because the grouping variable is carried on by default. Please see the dplyr
vignette:
分组影响动词如下:分组
select()
与未分组的select()
相同,但分组变量始终保留。
Grouping affects the verbs as follows: grouped
select()
is the same as ungroupedselect()
, except that grouping variables are always retained.
请注意(每个)总结
剥离一层分组(在您的情况下, j
) ,所以在总结
之后,您的数据仅按 i
分组,并将其输出到输出中。如果您不想要,可以在选择 s
之前取消分组数据:
Note that (each) summarize
peels off one layer of grouping (in your case, j
), so after the summarize
, your data is only grouped by i
and that is printed in the output. If you don't want that, you can ungroup the data before selecting s
:
require(dplyr)
df %>%
group_by(i,j) %>%
summarize(s=sum(x)) %>%
ungroup() %>%
filter(i==1) %>%
select(s)
#Source: local data frame [2 x 1]
#
# s
#1 1.129867
#2 1.265131
这篇关于dplyr:即使没有选择它,也可以获取group_by-column的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!