Home > database >  Find quantile-class for a sample value in R
Find quantile-class for a sample value in R

Time:07-18

I have this numeric vector of quantiles:

c(`0%` = -3.375, `10%` = 0.399999999999999, `20%` = 0.9299, `30%` = 1.25425, 
`40%` = 1.5333, `50%` = 1.77835, `60%` = 2.0138, `70%` = 2.26495, 
`80%` = 2.5633, `90%` = 3.2, `100%` = 10)

#
      0%      10%      20%      30%      40%      50%      60%      70%      80%      90%     100% 
-3.37500  0.40000  0.92990  1.25425  1.53330  1.77835  2.01380  2.26495  2.56330  3.20000 10.00000 

And I also do have a value like 7.2. Now I want to find the matching group, such that the value is greater than the lower limit and smaller or equal to the upper limit. What is an efficient (any) way to check that?

CodePudding user response:

Haven't done exhaustive tests, is this what you wanted?

> head(x[x>1],1)
    30% 
1.25425

and

> head(x[x>3],1)
90% 
3.2

CodePudding user response:

not sure if this is what you are looking for?

library(data.table)
# create a data.table
lookup <- as.data.table(my.v, keep.rownames = TRUE)
# create some handy extra columns
lookup[, `:=`(rn2 = shift(rn, type= "lead"),
              val2 = shift(my.v, type= "lead"))]
# create data.table with value to look up
DT <- data.table(value = 7.2)
# perform non-equi join
DT[lookup, `:=`(cat = paste(i.rn, i.rn2, sep = "-")), 
   on = .(value >= my.v, value < val2)][]

   value      cat
1:   7.2 90%-100%

CodePudding user response:

You can use findInterval which makes a binary search.

v <- 7.2
i <- findInterval(v, x)

x[i:(i 1)]
# 90% 100% 
# 3.2 10.0 

Data

x <- c(`0%` = -3.375, `10%` = 0.399999999999999, `20%` = 0.9299, `30%` = 1.25425, 
`40%` = 1.5333, `50%` = 1.77835, `60%` = 2.0138, `70%` = 2.26495, 
`80%` = 2.5633, `90%` = 3.2, `100%` = 10)
  • Related