Skip to content
Prev 262037 / 398502 Next

A Calculation on list object

Hi Ron,

Seems like there might be a really elegant way, but I would use
lapply().  For instance:

lapply(seq_along(List), function(x) List[[x]] + Vector[x])

If you do this regularly and want something that reads more
intuitively, consider defining an operator that does this.  %+% is
undefined (at least on my system), so something like:

set.seed(1)
List <- list(rnorm(5), rnorm(2), rnorm(7))
Vector <- 3:5

"%+%" <- function(e1, e2) {
  if (identical(length(e1), length(e2)))
    lapply(seq_along(e1), function(i) e1[[i]] + e2[[i]])
  else stop("length of e1 (", length(e1),
    ") must match length of e2 (", length(e2), ").")
}

List %+% Vector
List %+% 11:13

This has the advantage of looking more like how you are thinking (add
elements of the list to elements of the vector).

Hope this helps,

Josh
On Mon, Jun 6, 2011 at 3:10 PM, Ron Michael <ron_michael70 at yahoo.com> wrote: