how to determine the percentile that a given value has in a sample in R

Asked

Viewed 34 times

-1

Suppose I have a vector-shaped sample

x <-c(2,3,68,253,1,35,3,35,01,24,04,36,254,2,28,12,4,54,66,775,6,45,33,68,71)

I know if I make the command:

quantile(x, 0.75) R returns me the percentile P75.

but I would like to know for example in which percentile is located the element of value 35 of my set x?

R would answer a question like this? there is an inverse of the quantile command?

1 answer

2


There is no inverse function of quantile but it is not difficult to get the percentile of any value x0.

x0 <- 35

First it is determined with findInterval where is x0 in the vector x ordered. To have quantis, divide by the length of the vector.

onde1 <- findInterval(x0, sort(x))/length(x)
quantile(x, onde1)
# 60% 
#35.4 

x0 must correspond to a quantity below 60%, therefore the range on the left is opened.

onde2 <- findInterval(x0, sort(x), left.open = TRUE)/length(x)
quantile(x, onde2)
#  52% 
#33.96 

Closing the gap on the right wouldn’t do any good:

onde3 <- findInterval(x0, sort(x), rightmost.closed = TRUE)/length(x)
quantile(x, onde3)
# 60% 
#35.4 

Now calculate the requested value with approx.

qq <- quantile(x, probs = c(onde3, onde1))
xqq <- unname(qq)
yqq <- as.numeric(sub("%", "", names(qq)))

approx(xqq, yqq, xout = x0)
#$x
#[1] 35
#
#$y
#[1] 57.77778

Browser other questions tagged

You are not signed in. Login or sign up in order to post.