0

I have the following data frame:

library(tidyverse)
dat <- structure(list(motif = c("MA0002.2_RUNX1", "MA0002.2_RUNX1", 
"MA0002.2_RUNX1", "MA0002.2_RUNX1", "MA0029.1_Mecom", "MA0029.1_Mecom", 
"MA0029.1_Mecom", "MA0029.1_Mecom"), cell_type = c("Adipose", 
"Bonemarrow", "Pulmonary", "Vertebral", "Adipose", "Bonemarrow", 
"Pulmonary", "Vertebral"), score = c(-9.86201111303514, 35.057552338226, 
-29.6389757883848, 7.54179196588973, 11.1302803315903, -6.87498775985931, 
-0.949533749727933, -3.70277441518105)), class = c("tbl_df", 
"tbl", "data.frame"), .Names = c("motif", "cell_type", "score"
), row.names = c(NA, -8L))

dat
#> # A tibble: 8 x 3
#>   motif          cell_type    score
#>   <chr>          <chr>        <dbl>
#> 1 MA0002.2_RUNX1 Adipose    - 9.86 
#> 2 MA0002.2_RUNX1 Bonemarrow  35.1  
#> 3 MA0002.2_RUNX1 Pulmonary  -29.6  
#> 4 MA0002.2_RUNX1 Vertebral    7.54 
#> 5 MA0029.1_Mecom Adipose     11.1  
#> 6 MA0029.1_Mecom Bonemarrow - 6.87 
#> 7 MA0029.1_Mecom Pulmonary  - 0.950
#> 8 MA0029.1_Mecom Vertebral  - 3.70

What I want to do is to group_by motif and then sort by values within group in a motif descendingly.

The desired end result is this:

MA0002.2_RUNX1 Bonemarrow  35.1  
MA0002.2_RUNX1 Vertebral    7.54 
MA0002.2_RUNX1 Adipose    - 9.86 
MA0002.2_RUNX1 Pulmonary  -29.6  
MA0029.1_Mecom Adipose     11.1  
MA0029.1_Mecom Pulmonary  - 0.950
MA0029.1_Mecom Vertebral  - 3.70 
MA0029.1_Mecom Bonemarrow - 6.87 

I tried this by but failed: dat %>% group_by(motif) %>% arrange(desc(score))

What's the right way to do it?

scamander
  • 3,218
  • 3
  • 21
  • 49

1 Answers1

1

Is this what you're after?

dat %>% arrange(motif, desc(score));


#    # A tibble: 8 x 3
#  motif          cell_type    score
#  <chr>          <chr>        <dbl>
#1 MA0002.2_RUNX1 Bonemarrow  35.1
#2 MA0002.2_RUNX1 Vertebral    7.54
#3 MA0002.2_RUNX1 Adipose     -9.86
#4 MA0002.2_RUNX1 Pulmonary  -29.6
#5 MA0029.1_Mecom Adipose     11.1
#6 MA0029.1_Mecom Pulmonary   -0.950
#7 MA0029.1_Mecom Vertebral   -3.70
#8 MA0029.1_Mecom Bonemarrow  -6.87

If you only want to sort, there is no need for group_by.

Details: In your case, group_by(motif) does in fact group entries by motif, but it doesn't re-arrange them. To do that you'd still need dat %>% group_by(motif) %>% arrange(motif, desc(score)). But since you're not actually applying any transformation at the group level, group_by is redundant.

Maurits Evers
  • 42,255
  • 4
  • 27
  • 51