[R] Average calculations

arun smartpink111 at yahoo.com
Wed Jan 23 14:44:37 CET 2013


Hi,
Try this:
 x1<-x[rev(order(x$Names,x$Values)),]
do.call(rbind,tapply(x1$Values,list(x1$Names),head,2))
#             [,1]     [,2]
#CK113234 223.2966 222.6737
#CK113298 192.5964 187.7486
#CK114042 236.3939 232.0223
#CK116292 237.5936 228.0037
#CK116296 223.6372 210.6630

#The average
tapply(x1$Values,list(x1$Names),function(x) mean(head(x,2)))
#CK113234 CK113298 CK114042 CK116292 CK116296 
#222.9852 190.1725 234.2081 232.7987 217.1501 
A.K.



----- Original Message -----
From: Nico Met <nicomet80 at gmail.com>
To: R help <r-help at r-project.org>
Cc: 
Sent: Wednesday, January 23, 2013 8:03 AM
Subject: [R] Average calculations

Dear all,

I have a matrix with two columns: "Names" and "Values"

In names: there are 4 groups they are, CK113234, CK116296, CK116292 and
CK114042

I want to *sort values* (decreasing order) based on each group and
take average of the *top two numbers* in each of the groups.


> dput(x)
structure(list(Names = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 5L, 5L, 5L, 5L, 2L, 2L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("CK113234", "CK113298",
"CK114042", "CK116292", "CK116296"), class = "factor"), Values =
c(208.336033333333,
223.29665, 221.63255, 211.29735, 217.75112, 210.97916, 222.67365,
216.0822, 189.83685, 194.1595, 210.66298, 223.637183333333, 187.74864,
192.5964, 237.593625, 216.8277, 225.8966, 228.00374, 214.99454,
211.38114, 218.7659, 209.9958, 214.804133333333, 215.184489473684,
224.2446, 217.559878571429, 232.022291666667, 214.02384, 236.393875,
228.73522)), .Names = c("Names", "Values"), class = "data.frame", row.names
= c(NA,
30L))


The out put will look like following:

Names Values  CK113234 222,98  CK116296 217,14  CK116292 232,79  CK114042
234,2
Your help is appreciated.

Regards

Nico

    [[alternative HTML version deleted]]

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list