Ask Your Question
3

What is the method for ranking within groups in R?

asked 2021-12-05 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-02-14 10:00:00 +0000

plato gravatar image

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
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-12-05 11:00:00 +0000

Seen: 15 times

Last updated: Feb 14 '22