[R] Groups and bwplot
Sébastien Bihorel
pomchip at free.fr
Sat Aug 20 12:59:13 CEST 2011
Dear R-users,
A while ago, Deepayan Sarkar suggested some code that uses the group
argument in bwplot to create some 'side-by-side' boxplots
(https://stat.ethz.ch/pipermail/r-help/2010-February/230065.html). The
example he gave was relatively specific and I wanted to generalize his
approach into a function. Unfortunately, I seem to have some issues
passing the correct arguments to the panel function, and would greatly
appreciate any suggestions to solve these issues:
require(lattice)
mybwplot <- function(x,y,data,groups){
if (missing(groups)||is.null(groups)) {
groups <- NULL
ngroups <- 1
} else {
data[[groups]] <- as.factor(data[[groups]])
ngroups <- nlevels(data[[groups]])
}
mywidth <- 1/(ngroups+1)
mypanel <- function(x,y,groups,...){
if (missing(groups)||is.null(groups)) {
panel.bwplot(x,y,...)
} else {
panel.superpose(x,y,...)
}
}
mypanel.groups <- function(x,y,groups,ngroups,...){
if (missing(groups)||is.null(groups)){
NULL
} else {
function(x, y, ..., group.number) {
panel.bwplot(x+(group.number-0.5*(ngroups+1))/(ngroups+1),y, ...)}
}
}
bwplot(formula(paste(y,x,sep=' ~ ')),
data = data,
groups = 'Plant',
ngroups=ngroups,
pch = "|",
box.width = mywidth,
panel = mypanel,
panel.groups = mypanel.groups)
}
myCO2 <- CO2
myCO2$year <- 2011
summary(myCO2)
mybwplot('Type','uptake',myCO2) # works
mybwplot('Type','uptake',myCO2,'Treatment') # Error using packet 1,
'x' is missing
mybwplot('Type','uptake',myCO2,'year') # Error using packet 1, 'x' is missing
# Deepayan Sarkar suggested code (adapted to myC02)
# bwplot(uptake ~ Plant, data = myCO2, groups = Treatment,
# pch = "|", box.width = 1/3,
# panel = panel.superpose,
# panel.groups = function(x, y, ..., group.number) {
# panel.bwplot(x + (group.number-1.5)/3, y, ...)
# })
More information about the R-help
mailing list