[R] lapply with functions with changing parameters

Erik Iverson eriki at ccbr.umn.edu
Tue Jun 1 23:00:23 CEST 2010



Bunny, lautloscrew.com wrote:
> Dear all,
> 
> I am trying to avoid a for loop here and wonder if the following is
> possible:
> 
> I have a data.frame with 6 columns and i want to get a
> cross-correlogram (by using ccf) . Obivously ccf only accepts two
> columns at once and then returms a list. In fact, with a for loop i´d
> do the following
> 
> 
> for (i in 1:6) {
> 
> x[[i]]=ccf(mydf[,i],mydf[,6])
> 
> 
> }
> 
> Is there any chance to the same with lapply? e.g. lapply(mydf,"ccf",
> .... ) with ... respresenting the changing arguments for ccf
> functions (note only the first argument does actually change)

You don't give a reproducible example, but since you want to apply a 
function to a list, the answer is yes.  Just defining the function and 
the list is the trick, untested:

lapply(mydf[, 1:5], function(x) ccf(x, mydf[, 6]))



More information about the R-help mailing list