Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One method for ranking within groups in R is to use the ave() function. The syntax for the function is:

ave(x, by, FUN = function(x) ...)

where x is the vector or variable to be ranked, by is the grouping variable, and FUN is the ranking function (e.g., rank).

For example, suppose we have a data frame df with variables group and value, and we want to rank the value variable within each group:

df <- data.frame(group = c("A", "A", "B", "B", "B"), value = c(4, 2, 6, 8, 3))
df$rank <- ave(df$value, df$group, FUN = rank)

The resulting data frame will have a new variable rank that contains the rankings within each group:

  group value rank
1     A     4  2.0
2     A     2  1.0
3     B     6  2.5
4     B     8  4.0
5     B     3  1.0