user4634071
user4634071

Reputation:

Ranking data frame

Her is my data:

x<- data.frame(P=c("M","C","M","C","C","M","C","M"),
    Q=c(13,12,12,14,19,15,12,11),
    R=c(15,13,21,32,32,21,13,32),
    T=c(15,12,12,14,12,11,19,15))

I want to calculate means for variables within each category. For example means for Q is: M= (13+12+15+11)= 12.75 and for C= (12+14+19+12)= 14.25 and so on.

Next, I want to rank the means for each variable and get the following table:

P   Q   R   T
M   2   2   2
C   1   1   1

I want to get equal rank for my real data. For example. if I have three 12, all will get the same rank

Upvotes: 1

Views: 92

Answers (3)

David Arenburg
David Arenburg

Reputation: 92310

For completeness, here's a possible data.table solution using frank from the devel version on GitHub

For means

library(data.table) ## v >= 1.9.5
(Res <- setDT(x)[, lapply(.SD, mean), by = P])
#    P     Q     R     T
# 1: M 12.75 22.25 13.25
# 2: C 14.25 22.50 14.25

For ranks

Res[, 2:4 := lapply(-.SD, frank, ties.method = "dense"), .SDcols = 2:4]
Res
#    P Q R T
# 1: M 2 2 2
# 2: C 1 1 1

Upvotes: 2

akrun
akrun

Reputation: 887991

You can try

aggregate(.~P, x, mean)

Or

library(dplyr)
x1 <-   x %>%
          group_by(P) %>%
           summarise_each(funs(mean)) 
x1
# P     Q     R     T
#1 C 14.25 22.50 14.25
#2 M 12.75 22.25 13.25

For ranking

x1 %>%
    mutate_each(funs(rank(-.)), Q:T)
#  P Q R T
#1 C 1 1 1
#2 M 2 2 2

Update

Suppose if there are ties,

 x1$Q[2] <- x1$Q[1]

rank will get the ties averaged by default. You can specify the ties.method to min or use min_rank

  x1 %>% 
     mutate_each(funs(min_rank(-.)), Q:T)
  #  P Q R T
  #1 C 1 1 1
  #2 M 1 2 2

Upvotes: 2

Veerendra Gadekar
Veerendra Gadekar

Reputation: 4472

to get the mean you can do this

do.call(rbind,lapply(split(x, f = x$P), function(x) data.frame(P = unique(x$P), Q = mean(x$Q), R = mean(x$R), T = mean(x$T))))

Upvotes: 1

Related Questions