[R] help converting for loop to vector operation

Avram Aelony aavram at mac.com
Wed Apr 29 22:58:56 CEST 2009



Dear List,

Hadley offered the following solution:

>library(plyr) 
>l_ply(2:6, draw_metric_by_date, df = economics, smooth = TRUE, BASEPATH = basepath) 

Many thanks,
Avram



 
On Wednesday, April 29, 2009, at 12:59PM, "Avram Aelony" <aavram at mac.com> wrote:
>
>Dear List, 
> 
>I have a wrapper function that draws a graph that I'd like to use in a vector-like manner.  The for-loop version I currently use is below. 
>
>library(ggplot2)
>data(economics)
>h <- 600
>w <- 800
>
>#----------------------------------------------------------
>draw_metric_by_date <- function( df, i, smooth=FALSE, BASEPATH ) {
>        mlabel  <- names(df)[i]
>        qmetric <- qplot( data=df, x=date, y=df[,i], geom=c('line','jitter'), ylab=mlabel, main=mlabel, colour=I("dark blue") )
>
>        if ( smooth == TRUE ) {
>                print("smoother requested...")
>                tmp     <- qmetric
>                qmetric <- tmp + stat_smooth()
>        }
>        
>
>        pngfn <- paste( BASEPATH, mlabel, ".png", sep="")
>        print(pngfn)
>        png( file=pngfn, height=h, width=w )
>                print(qmetric)
>                dev.off()
>}
>
>
>basepath <- "C:/tmp"
>for ( i in c(2:6) ) {
>        print(names(economics)[i])
>        draw_metric_by_date( economics, i, smooth=TRUE, basepath )
>}
>
>Could someone show me how to do the same with a vector approach with an "apply" function ? 
>
>Many thanks,
>Avram
>
>______________________________________________
>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.
>
>




More information about the R-help mailing list