Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse quantile for scores in tidyverse

Tags:

dataframe

r

dplyr

I want to ranks quantiles for my data, but I get the high rank for the highest score. I want to get the lowest rank (i.e., 1) for the highest score.

The following code gives me a high rank for the highest score, which I am not interested in:

M %>%
    mutate(quantile = ntile(Score, 10))

I have used reverse= TRUE, or include.lowest = TRUE, did not work. Can you help me? I felt that it is not necessary to provide a sample of data.


1 Answers

Just negate the values:

M %>% mutate(quantile = ntile(-Score, 10))

Example:

df1 %>%
  mutate(quantile = ntile(-score, 3))

# # A tibble: 6 x 4
#   ntile date        score quantile
#   <int> <date>      <dbl>    <int>
# 1     1 2005-08-31 -2.39         3
# 2     1 2005-09-30  0.573        2
# 3     1 2005-10-31 -1.61         3
# 4     1 2005-11-30  5.43         1
# 5     1 2005-12-31  0.106        2
# 6     1 2006-01-31  6.66         1  

Toy Data:

df1 <- structure(list(ntile = c(1L, 1L, 1L, 1L, 1L, 1L), 
                      date = structure(c(13026, 13056, 13087, 13117, 13148, 13179), 
                                       class = "Date"), 
                      score = c(-2.38916419707325, 0.572675136581781, -1.61130358515631, 
                                 5.42706994951004, 0.105533424368025, 6.65697289481407)), 
                 row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"))
like image 147
M-- Avatar answered Sep 04 '25 05:09

M--



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!