4

is there a quick way in R to assign to each value in a given vector the corresponding decile ?

For example an arbitrary input vector should be transformed like the following.

in  <- rnorm(10)

>  [1]  9  2 10  5  3  4  8  1  7  6

cheers.

csgillespie
  • 59,189
  • 14
  • 150
  • 185
Peanut
  • 803
  • 1
  • 11
  • 24

2 Answers2

3

Use the quantile function to get the deciles

deciles = quantile(ran, seq(0, 1, 0.1))

Then use cut to put your data into the correct deciles

ran_dec = cut(ran, deciles, include.lowest = TRUE)

Since ran_dec is a factor, just use

as.numeric(ran_dec) 

to convert to a number.

csgillespie
  • 59,189
  • 14
  • 150
  • 185
1

Alternatively, you can use dplyr's ntile function easily:

dplyr::ntile(rnorm(10), 10)
# [1] 10  5  2  1  9  3  4  8  7  6
talat
  • 68,970
  • 21
  • 126
  • 157