Reputation: 1965
I have a list of percentiles and I wish to query a nearest value from it by specifying a probability and vice versa. Consider the following code:
samples <- runif(1000, 0, 1)
percentiles <- quantile(samples,probs=(0:100)/100)
plot(percentiles)
I can easily read the plot(e.g. 50% prob -> 0.5 in this example), however how can I find the nearest value in the list (either by specifying the probability or the value on the Y-axis) ?
Thanks!
Upvotes: 0
Views: 97
Reputation: 99331
Building off Robert's answer, you can look at all the neighbors with this. Coincidentally, the result is in list
form.
> zzz <- sapply(1:(length(percentiles)-1), function(i){
c(sort(percentiles)[i-1], sort(percentiles)[i+1])
}, USE.NAMES = TRUE)[-1]
The use of USE.NAMES
allows you to access the neighbors easily via the list index.
> zzz[99] ## neighbors of the 99th percentile
## 98% 100%
## 0.9861953 0.9986512
> zzz[25] ## neighbors of the 25th percentile
## 24% 26%
## 0.2654937 0.2926444
> zzz[36] ## neighbors of the 36th percentile
## 35% 37%
## 0.3756176 0.3864981
Upvotes: 2
Reputation: 9344
Sort first and look at the neighbors.
i <- 50
sorted_percentiles <- sort(percentiles)
# the values adjacent to the 50th data point are:
sorted_percentiles[i - 1]
sorted_percentiles[i + 1]
Upvotes: 2