[R] help converting for loop to vector operation

Avram Aelony aavram at mac.com
Wed Apr 29 21:59:39 CEST 2009


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




More information about the R-help mailing list