ZRoss
ZRoss

Reputation: 1479

dplyr arrange not arranging by groups

In this super-simple code I expect dplyr to arrange first by my grouping variable (blonde) and then by age, but it does not seem to be accounting for the grouping variable at all. I'm pretty sure this has worked differently for me in the past. What I want (and expect) is that it would arrange by blonde first (since this is the grouping variable) and then age. I'm using dplyr_0.5.0. When I test with mutate on the grouping variable it behaves as expected computing a group-wise mean.

I know that I can arrange by both blonde and age, but I thought a previous version of dplyr would account for the grouping variable when using arrange am I misremembering?

# In this code I expect it to order by the grouping
# variable first (blonde) then age.
df <- data.frame(blonde = c(0,1,0,1), 
                 age=24:21)

group_by(df, blonde) %>% arrange(age)

Source: local data frame [4 x 2]
Groups: blonde [2]

  blonde   age
   <dbl> <int>
1      1    21
2      0    22
3      1    23
4      0    24

Upvotes: 3

Views: 1999

Answers (1)

SCDCE
SCDCE

Reputation: 1643

You can force it to use the group:

df <- data.frame(blonde = c(0,1,0,1), 
                 age=24:21)

group_by(df, blonde) %>% arrange(age, .by_group = TRUE)

# A tibble: 4 x 2
# Groups:   blonde [2]
  blonde   age
   <dbl> <int>
1      0    22
2      0    24
3      1    21
4      1    23

Upvotes: 6

Related Questions