[R] Newbie: how to get unique x unique x aggregate chart?

Chuck Cleland ccleland at optonline.net
Wed Nov 15 16:21:47 CET 2006


Christian Convey wrote:
> I'm very new to R, so please forgive me if I just missed the answer in
> existing documentation...
> 
> I have a data set with at least three columns, X, Y, and Z.
> 
> I want to produce a chart where one axis shows all the unique values of X,
> and the other axis shows all the unique values of Y.  Each cell within the
> chart should contain the result of applying an aggregate function (such as
> mean(), for example) to Z value of those rows that are associated with that
> cell (via their X and Y values).
> 
> Can someone recommend a good way to do this?

  I'm not sure exactly what kind of chart you want, but this may give
you some ideas.

library(reshape) # Provides melt() and cast()

df <- data.frame(X = rep(c("A","B","C","D"), each = 40),
                 Y = rep(1:4, 40),
                 Z = runif(160))

df <- melt(df, measure.var="Z")

newdf <- cast(df, X + Y ~ ., fun.aggregate = mean)

library(lattice) # Provides barchart and bwplot()

barchart(value ~ X | Y, data = newdf, layout=c(4,1,1))

barchart(value ~ X, groups=Y, data = newdf, auto.key=TRUE)

  Also, you might consider this which shows much more than the location
of Z:

bwplot(Z ~ X | Y, data = df, layout=c(4,1,1))

  Finally, here is another possibly useful way to aggregrate df (an
alternative to melt() and cast() which gives a different structure):

with(df, tapply(Z, list(X,Y), mean))

> Thanks very much,
> Christian
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at stat.math.ethz.ch 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.
> 

-- 
Chuck Cleland, Ph.D.
NDRI, Inc.
71 West 23rd Street, 8th floor
New York, NY 10010
tel: (212) 845-4495 (Tu, Th)
tel: (732) 512-0171 (M, W, F)
fax: (917) 438-0894



More information about the R-help mailing list