[R] how to calculate the product of every two elements in two vectors

Gabor Grothendieck ggrothendieck at gmail.com
Sat Jul 24 19:15:34 CEST 2010


On Fri, Jul 23, 2010 at 11:11 AM, aegea <gcheer3 at gmail.com> wrote:
>
> Thanks in advance!
>
> A=c(1, 2,3)
> B=c (9, 10, 11, 12)
>
> I want to get C=c(1*9, 1*10, 1*11, 1*12, ....., 3*9, 3*10, 3*11, 3*12)?
> C is still a vector with 12 elements
> Is there a way to do that?

Here are yet a few more.  The first one is the only one so far that
uses a single function and the last two are slight variations of ones
already posted.

kronecker(A, B)

c(tcrossprod(B, A))

c(outer(B, A))

c(B %o% A)

Here is a speed comparison.  The fastest are as.matrix, %outer% and
%o% .  They are so close that random fluctuations might easily change
their order and since %o% involves the least keystrokes that one might
be a good overall choice.  Although not among the fastest the
kronecker solution is the simplest since it only involves a single
function call so it might be preferred on that count.

> A <- B <- 1:400
> out <- benchmark(
+ as.matrix =  c(as.matrix(B) %*% A),
+ crossprod = c(tcrossprod(B, A)),
+ outer = c(outer(B, A)),
+ o = c(B %o% A),
+ kronecker = kronecker(A, B),
+ touter = as.vector(t(outer(A, B))))
> out[order(out$relative), ]
       test replications elapsed relative user.self sys.self
user.child sys.child
1 as.matrix          100    0.92 1.000000      0.62     0.28
NA        NA
3     outer          100    0.93 1.010870      0.59     0.35
NA        NA
4         o          100    0.94 1.021739      0.66     0.28
NA        NA
2 crossprod          100    1.11 1.206522      0.67     0.43
NA        NA
5 kronecker          100    1.45 1.576087      1.25     0.21
NA        NA
6    touter          100    1.84 2.000000      1.40     0.43
NA        NA



More information about the R-help mailing list