Skip to content

A Calculation on list object

3 messages · Ron Michael, Joshua Wiley, Gabor Grothendieck

#
Hello, I am into some calculation on a list object, therefore requesting the peers if there is any short cut way to so the same calculation.

Let say I have following list object:
[[1]]
[1] -0.6264538  0.1836433 -0.8356286  1.5952808  0.3295078

[[2]]
[1] -0.8204684  0.4874291

[[3]]
[1]  0.7383247  0.5757814 -0.3053884  1.5117812  0.3898432 -0.6212406 -2.2146999
[1] 3 4 5

Now, what I want to do is, add List with Vector, element-by-element. Means I wanted to do:
[1] 2.373546 3.183643 2.164371 4.595281 3.329508
[1] 3.179532 4.487429
[1] 5.738325 5.575781 4.694612 6.511781 5.389843 4.378759 2.785300

Till now I have done this calculation with for-loop. Therefore it would be interesting if there is any elegant way to do the same.

Thanks,
#
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:

  
    
#
On Mon, Jun 6, 2011 at 6:10 PM, Ron Michael <ron_michael70 at yahoo.com> wrote:
Try this:

mapply("+", List, Vector)