dplyr: getting group_by-column even when not selecting it

后端 未结 1 1282
抹茶落季
抹茶落季 2021-01-21 10:31

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,         


        
相关标签:
1条回答
  • 2021-01-21 11:17

    That's because the grouping variable is carried on by default. Please see the dplyr vignette:

    Grouping affects the verbs as follows: grouped select() is the same as ungrouped select(), except that grouping variables are always retained.

    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
    
    0 讨论(0)
提交回复
热议问题