I have a dataframe that is nested by groups. I want to convert variable 'x' from its raw value to quantile position (20%, 40%, 60%, 80%, 100% or 1, 2, 3, 4, 5).
Here is an example of the data I'm using:
df <- data.frame(x=c(1, 5, 21, 24, 43, 47, 56, 59, 68, 69, 11, 15, 25, 27, 48, 49, 51, 55, 61, 67),
y=c("A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B"))
This is what I have tried:
df$z <- aggregate(df$x, by = list(df$y), FUN = function(x) quantile(x, probs = c(0.2, 0.4, 0.6, 0.8, 1), na.rm = T))
In essence, I would like to create a new variable that looks like this:
df$z <- c(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5)