4

I have a data in the t vector and given the data I can get quantile

   t = c(1,2,3,4,5,6,3,2,21,22,23,2,23,4,4,4444)
  quantile(t,c(.3))
3

But I would like to do the opposite

I want provide 3 and have it return the quantile percentage

like somefunction(3,t) and the output is 30%

Is there a function for that?

user3022875
  • 8,598
  • 26
  • 103
  • 167
  • You are asking for the `ecdf` function, which is offered as the inverse of quantile on the `?quantile` help page. It is returned as a decimal fraction but if you wanted it displayed as a "percentage" then just multiply by 100. (I suspect this is a duplicate.) – IRTFM Oct 05 '16 at 17:29

2 Answers2

7

Using the definition of the quantile:

sum(x<=3)/length(x)

gives you: 0.375

Equivalent

f <- ecdf(x)
f(3) #0.375
Rentrop
  • 20,979
  • 10
  • 72
  • 100
4

If x is the vector, and x0 is the value you want to check, we can use

match(x0, sort(x)) / (length(x) + 1)

For your example:

x <- c(1,2,3,4,5,6,3,2,21,22,23,2,23,4,4,4444)
match(3, sort(x)) / (length(x) + 1)
# [1] 0.2941176
Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248