Suppose I have the following data:
id grpvar1 grpvar2 value
1 1 3 7.6
2 1 2 4
...
3 1 5 2
For each id
, I want to compute the percent_rank()
of its value
within the group defined by the combination of grpvar1
and grpvar2
.
Using data.table
, I would go (assuming I my data is in a data.frame
called dataf
:
library(data.table)
# Make dataset into a data.table.
dt <- data.table(dataf)
# Calculate the percentiles.
dt[, percrank := rank(value)/length(value), by = c("grpvar1", "grpvar2")]
What is the equivalent in dplyr
?
Try:
library(dplyr)
dataf %>%
group_by(grpvar1, grpvar2) %>%
mutate(percrank=rank(value)/length(value))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With