You may want to consult a recent post by Felix
(https://stat.ethz.ch/pipermail/r-help/2011-August/286707.html) on how
to pass group parameter.
Weidong Gu
On Sat, Aug 20, 2011 at 6:59 AM, S?bastien Bihorel <pomchip at free.fr>
wrote:> 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, ...)
> # ? ? ? ?})
>
> ______________________________________________
> 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.
>