How to order grouped rows while keeping duplicates together

Viewed 325

I have a dataframe with several "people".
There are repeat instances for "people", however, the measured "value" is different in each instance.

Here is an example of dataframe.

df2 <- data.frame(
  value = c(1, 2, 3, 4, 5), 
  people = c("d", "c", "b", "d", "b")
)

which looks like:

  value people
     1      d
     2      c
     3      b
     4      d
     5      b

I would like to group the data by "people", then sort the groups of rows by "value", and within the groups, I would like to sort descending by the "value".

That is, I want to keep duplicates together while sorting by value.

Here is how I would like the data to look:

  value people
     1      d
     4      d
     2      c
     3      b
     5      b 

I have tried multiple attempts with group_by and arrange using {dplyr} but seems I am missing something.
Thanks for the help.

I have made a change - for clarity, I do not want "people" sorted alphabetically - this is a schedule in reality - person D has the first appointment (1), and his second appointment is 4. I want them to appear first and together. Person C has a 2nd appointment. Person B has a 3rd appointment, his other appointment is 5. I hope this makes it more clear. Thanks again

3 Answers

You can use arrange in this form :

library(dplyr)

df2 %>% 
  arrange(value) %>%
  arrange(match(people, unique(people)))

#  value people
#1     1      d
#2     4      d
#3     2      c
#4     3      b
#5     5      b

Though a longer code, but this will also work

df2 %>% group_by(people) %>% arrange(value) %>%
 mutate(d = first(value)) %>% arrange(d) %>% ungroup() %>% select(-d)

# A tibble: 5 x 2
  value people
  <dbl> <chr> 
1     1 d     
2     4 d     
3     2 c     
4     3 b     
5     5 b 

I got your result with the following one-liner base-R code:

df2[order(df2$people, decreasing = TRUE),]

#  value people
# 1     1      d
# 4     4      d
# 2     2      c
# 3     3      b
# 5     5      b
Related