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.
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.
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.
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