Cross Validated is a question and answer site for people interested in statistics, machine learning, data analysis, data mining, and data visualization. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

In R, given a set of numerical data, how do I decide the top 1% of these data, and replace them with a new value, say, e.g. $10^{10}$

share|improve this question
up vote 10 down vote accepted

You could do this:

### x will be whatever variable you want to do this to. I'm replacing 
### the top 1% with 1e10. 
qnt = quantile(x,.99)
w = which(x >= qnt) 
x[w] = 1e10

More generally implemented as a function:

### x is the input data. This function replaces the top 'perc' percent
### with the value 'rp'. = function(x, perc, rp)
   qnt = quantile(x,1-perc)
   w = which(x >= qnt) 
   x[w] = rp
share|improve this answer
Or, even more concisely (densely) as a one-liner x[x>=quantile(x,0.99)] <- 1e10. – cardinal Feb 6 '12 at 3:10
(+1) As a function: <- function(x,p,r) { x[x>=quantile(x,1-p)] <- r; x} – cardinal Feb 6 '12 at 3:15
(+1, cardinal) Is there anything more computationally efficient about what you've written (or are there just bonus points for making it a single line)? – Macro Feb 6 '12 at 3:22
Note also that if there are a very large number of ties in x, then basing the replacement on quantiles might not work as expected. An alternative would be x[rank(x,ties.method="first")>=(1-p)*length(x)] <- r but in the "typical" case where the values of x are fairly "continuous", I think the previous approach using quantiles is better. – cardinal Feb 6 '12 at 3:53
The answers and comments above are good answers. Depending on what the questioner is ultimately looking for @Luna may also be interested in the literature on winsorized means and variances and that there are several implementations in various R packages (eg in Wilcox's WRS package associated with his excellent book Modern Statistics for the Social and Behavioral Sciences.) – Peter Ellis Feb 6 '12 at 10:14

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.