[R] Is there a simpler way to do this?
Marc Schwartz
marc_schwartz at comcast.net
Wed Nov 21 02:21:25 CET 2007
On Tue, 2007-11-20 at 17:13 -0800, Anup Nandialath wrote:
> Dear Friends,
>
> My objective is to do element wise multiplication of two vectors. For example suppose I have
>
> a <- (1,1,1)
> b <- (2,4)
>
> My output should be (2,4,2,4,2,4). I managed to write it down with loops as follows
>
> r <- c(1,1,1)
> l <- c(2,4)
> x <- 1
> for (j in 1:3)
> {
> for (i in 1:2)
> {
> new[x,] <- r[j]*l[i]
> x <- x+1
> }
> }
>
>
> Is there a simpler solution to this without using the loops?
>
>
> Thanks and Regards
>
> Anup
Try this:
> as.vector(t(a %o% b))
[1] 2 4 2 4 2 4
See ?outer for more information.
HTH,
Marc Schwartz
More information about the R-help
mailing list