RE: [R] Automating plot labelling in custom function in lapply( ) ?

From: Liaw, Andy <andy_liaw_at_merck.com>
Date: Fri 29 Apr 2005 - 23:34:12 EST


> From: Marc Schwartz
>
> On Fri, 2005-04-29 at 13:00 +0100, Gavin Simpson wrote:
> > Dear List,
> >
> > Consider the following example:
> >
> > dat <- data.frame(var1 = rnorm(100), var2 = rnorm(100),
> > var3 = rnorm(100), var4 = rnorm(100))
> > oldpar <- par(mfrow = c(2,2), no.readonly = TRUE)
> > invisible(lapply(dat,
> > function(x) {
> > plot(density(x),
> > main = deparse(substitute(x))) }
> > )
> > )
> > par(oldpar)
> >
> > I want to the main title in each of the density plots to be
> var1, var2,
> > etc. The above code produces x[[1]], x[[2]] etc.
> >
> > What do I need to modify to be able to use the name of x as
> the plot
> > label within in the above situation?
> >
> > Thanks in advance,
> >
> > Gav
>
> Gavin,
>
> To paraphrase John Fox from a recent thread, "this is one of
> those times
> where trying to avoid using a for() loop is counterproductive":
>
> oldpar <- par(mfrow = c(2,2), no.readonly = TRUE)
>
> for (i in 1:4)
> {
> plot(density(dat[, i]), main = colnames(dat)[i])
> }
>
> par(oldpar)
>
>
> HTH,
>
> Marc Schwartz

For things like these I'd suggest using lattice; e.g.,

densityPlot <- function(dat, xlab=deparse(substitute(dat)), ...) {

    stopifnot(require(lattice))
    vars <- rep(colnames(dat), each=nrow(dat))     densityplot(~ c(as.matrix(dat)) | vars, xlab=xlab, ...) }

densityPlot(dat, layout=c(2, 2))

Cheers,
Andy  

> ______________________________________________
> R-help@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
>
>
>



R-help@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 Received on Fri Apr 29 23:43:05 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:31:31 EST