Re: [S] SUMMARY:: Summarizing replicate data

John Wallace (jrw@fish.washington.edu)
Thu, 14 May 1998 03:29:29 -0700 (PDT)


Here's a late entry: agg() [attached below] works like aggregate(), but the
restriction of using only one function at a time is removed.

Thus, the following works;

> attach(cu.summary) #Automobile Data from Consumer Reports
> agg(list(Price=Price), list(Country=Country, Type=Type), c("mean", "median"))

Country Type mean median
1 France Compact 15930.000 15930.0
2 Germany Compact 24785.000 24320.0
3 Japan Compact 13506.000 11650.0
4 Japan/USA Compact 11922.750 11866.5
5 Sweden Compact 20796.667 18450.0
6 USA Compact 9824.714 9995.0
7 USA Large 21499.714 20225.0
8 England Medium 23550.000 23550.0
9 France Medium 19945.000 19945.0
10 Germany Medium 33350.000 33200.0
11 Japan Medium 26742.833 24030.0
....

And with,

Mean <- function(x)
{
mean(x, na.rm = T)
}

Var <- function(x)
{
if(length(x) == 1)
return(0)
var(x, na.method = "omit")
}

and

N <- function(x)
{
length(x[!is.na(x)])
}

we can get:

> agg(list(Price=Price), list(Country=Country, Type=Type), c("Mean","Var","N"))

Country Type Mean Var N
1 France Compact 15930.000 0.0 1
2 Germany Compact 24785.000 27242566.7 4
3 Japan Compact 13506.000 14451577.0 3
4 Japan/USA Compact 11922.750 209526.9 4
5 Sweden Compact 20796.667 28880758.3 3
6 USA Compact 9824.714 767552.2 7
7 USA Large 21499.714 33940853.2 7
8 England Medium 23550.000 0.0 1
9 France Medium 19945.000 0.0 1
10 Germany Medium 33350.000 42592500.0 3

....

----------------------------------

"agg" <- function(data, by, FUNS)
{
#
# DATE WRITTEN: 14 May 1998
# AUTHOR: John R. Wallace (jrw@fish.washington.edu)
#
out <- aggregate.data.frame(data, by, eval(parse(text = FUNS[1])))
for(i in 2:length(FUNS)) {
tmp <- aggregate.data.frame(data, by,
eval(parse(text = FUNS[i])))
tmp <- tmp[, ncol(tmp)]
out <- cbind(out, tmp)
}
dimnames(out)[[2]][ - (1:length(by))] <- FUNS
out
}

-- 
John Wallace
University of Washington                    ^    ^    ^
Fisheries Research Institute               / \  / \  / \   ^
Box 357980                                 / \  / \   |   / \
Seattle, WA 98195-7980                      |    |  o__~  / \
PHONE   (206) 543-1513                  @ @         /\/\   |
FAX     (206) 685-7471                   ~    
E-MAIL        jw@u.washington.edu              o
WWW      http://www.fish.washington.edu/people/jrw/Wallace.html 
                                                o  _///_ //
                                                <`)=  _<<
                                                    \\\  \\
-----------------------------------------------------------------------
This message was distributed by s-news@wubios.wustl.edu.  To unsubscribe
send e-mail to s-news-request@wubios.wustl.edu with the BODY of the
message:  unsubscribe s-news