Home dplyr: Arrange not behaving as expected after group_by and summarize
Reply: 0

dplyr: Arrange not behaving as expected after group_by and summarize

user866
1#
user866 Published in June 25, 2018, 12:03 am

I must be missing something with how group_by levels in dplyr get peeled off. In the example below, I group by 2 columns, summarize values into a single variable, then sort by that new variable:

mtcars %>% group_by( cyl, gear ) %>% 
  summarize( hp_range = max(hp) - min(mpg)) %>% 
  arrange( desc(hp_range) )

# Source: local data frame [8 x 3]
# Groups: cyl [3]
#
#    cyl  gear  hp_range
#  (dbl) (dbl) (dbl)
#1     4     4  87.6
#2     4     5  87.0
#3     4     3  75.5
#4     6     5 155.3
#5     6     4 105.2
#6     6     3  91.9
#7     8     5 320.0
#8     8     3 234.6

Obviously this is not sorted by hp_range as intended. What am I missing?

EDIT: The example works as expected without the call to desc in arrange. Still unclear why?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.312587 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO