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:
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:
List <- vector('list', length = 3)
set.seed(1)
List[[1]] <- rnorm(5)
List[[2]] <- rnorm(2)
List[[3]] <- rnorm(7)
List
[[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
Vector <- 3:5 Vector
[1] 3 4 5 Now, what I want to do is, add List with Vector, element-by-element. Means I wanted to do:
List[[1]] + Vector[1]
[1] 2.373546 3.183643 2.164371 4.595281 3.329508
List[[2]] + Vector[2]
[1] 3.179532 4.487429
List[[3]] + Vector[3]
[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,
______________________________________________ R-help at r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Joshua Wiley Ph.D. Student, Health Psychology University of California, Los Angeles http://www.joshuawiley.com/