[R] Multiply List by a Numeric
Marc Schwartz
marc_schwartz at me.com
Mon Aug 24 18:10:41 CEST 2009
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
More information about the R-help
mailing list