On Aug 24, 2009, at 10:58 AM, Brigid Mooney wrote:
I apologize for what seems like it should be a straighforward query.
I am trying to multiply a list by a numeric and thought there would
be a
straightforward way to do this, but the best solution I found so far
has a
for loop.
Everything else I try seems to throw an error "non-numeric argument to
binary operator"
Consider the example:
a <- 1
b <- 1:2
c <- 1:3
abc <- list(a,b,c)
To multiply every element of abc by a numeric, say 3, I wrote a for-
loop:
for (i in 1:length(abc))
{
abc[[i]] <- 3*abc[[i]]
}
Is this really the simplest way or am I missing something?
Thanks!
Try:
> abc
[[1]]
[1] 1
[[2]]
[1] 1 2
[[3]]
[1] 1 2 3
> lapply(abc, "*", 3)
[[1]]
[1] 3
[[2]]
[1] 3 6
[[3]]
[1] 3 6 9
See ?lapply for more information.
HTH,
Marc Schwartz
______________________________________________
R-help@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.