I'm want to rank the euclid_dist of combinations, grouped by pitch_2 in my dataframe from smallest to largestg. My dataframe has over 80million combinations a bunch of different pitch_2s which is my I'm grouping them by that. But the ordering seems almost random where the smallest euclid_dist isn't getting the #1 rank when I look at my data. I thought maybe it was an issue of some being below 1 and it was starting the counting then but it doesn't even work for values larger than 1.
This is the command I'm running to do the ranking
data <- data %>% group_by(pitch_2) %>%
mutate(rank = order(euclid_dist))
but this is what my dataframe looks like afterwards -- it correctly starts at 1 for each pitch_2 when ranking but the rankings themselves are out of whack and I'm not sure how to modify order or whether there is a better approach
> head(data)
# A tibble: 6 x 4
# Groups: pitch_2 [1]
pitch_1 pitch_2 euclid_dist rank
<fct> <fct> <dbl> <int>
1 429721-CU 493247-SI 2.53 15
2 114849-FC 493247-SI 3.52 6
3 430599-FF 493247-SI 3.49 14
4 458567-FF 493247-SI 2.59 27
5 435261-CU 493247-SI 3.10 8
6 425629-CU 493247-SI 2.14 17
We need rank
instead of order
. According to ?rank
Returns the sample ranks of the values in a vector.
library(dplyr)
data %>%
group_by(pitch_2) %>%
mutate(rank = order(euclid_dist))
# A tibble: 6 x 4
# Groups: pitch_2 [1]
# pitch_1 pitch_2 euclid_dist rank
# <chr> <chr> <dbl> <dbl>
#1 429721-CU 493247-SI 2.53 2
#2 114849-FC 493247-SI 3.52 6
#3 430599-FF 493247-SI 3.49 5
#4 458567-FF 493247-SI 2.59 3
#5 435261-CU 493247-SI 3.1 4
#6 425629-CU 493247-SI 2.14 1
data <- structure(list(pitch_1 = c("429721-CU", "114849-FC", "430599-FF",
"458567-FF", "435261-CU", "425629-CU"), pitch_2 = c("493247-SI",
"493247-SI", "493247-SI", "493247-SI", "493247-SI", "493247-SI"
), euclid_dist = c(2.53, 3.52, 3.49, 2.59, 3.1, 2.14), rank = c(15L,
6L, 14L, 27L, 8L, 17L)), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))