[R] lapply-related question

Prof Brian D Ripley ripley at stats.ox.ac.uk
Mon Sep 9 18:17:20 CEST 2002


On Mon, 9 Sep 2002, Ott Toomet wrote:

> Dear R-gurus,
>
> I would like to use a lapply on a kind of "bivariate" problem.  I have
> a vector and a list, components of which are vectors, e.g.
>
> vec <- c(1,2,3)
> lst <- list(1, c(2,3), c(4,5,6))
>
> I want to apply a function to each component of the list, using the
> corresponding component of the vector as a parameter.  E.g. I want a
> list in the form
>
> list(lst[[1]] + vec[1], lst[[2]] + vec[2], .... )
>
> I think this can be achieved with a cycle and probably using lapply
> with a function, storing the index in an outer environment as
>
> i <- 1
> lapply(lst, FUN=function(x) {x + vec[i]; i <<- i + 1})
>
> but are there any more cleaner solution?

Use

lapply(seq(along=lst).  function(i, vec, lst){body}, vec=vec, lst=lst)

using the index i in the body.

Or just use a for loop.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list