Skip to content
Prev 75612 / 398502 Next

How to repeat code snippet for several variables in a data frame?

Sander Oom wrote:

            
Many ways, a very basic one is to make it a function with an argument 
corresponding to names of columns of the data.frame (code given below).

Uwe Ligges



do_it <- function(varname){
     library(lattice)
     tmp <- aggregate(test[[varname]], list(test$bins, test$groups), mean)
     colnames(tmp) <- c("bins", "groups", "abc")
     tmp
     #pltName <- paste("line_datGrassChem_", "abc", ".eps", sep="")
     #postscript(pltName)
     labs <- c("-15/-9","-9/-6","-6/-3","-3/0")
     sps <- trellis.par.get("superpose.symbol")
     sps$pch <- 1:4
     trellis.par.set("superpose.symbol", sps)
     xyplot( abc ~ bins, data = tmp,
         groups = groups, type = list("p", "l"),
         scales = list(x = list(labels=labs)),
         layout = c(1,1),
         key = list(columns = 4,
         text = list(paste(unique(tmp$groups))),
         points = Rows(sps, 1:4)
         )
     )
     #dev.off()
}

do_it("ghi")