Reputation: 21
I have two vectors: numbers1 and numbers2 with integer elements in them. I want to calculate the element wise products of numbers1 and numbers2. For example, in numbers1, the first value is 3 and in numbers2 the first value is 2. What would be the syntax?
This reminds me of array elements in Java but I'm unable to conclude how to multiply them. I am new to R programming.
Upvotes: 0
Views: 386
Reputation: 1432
In R the simple vector multiplication gives you element wise multiplication
>a=c(1,2,3)
>b=c(1,2,3)
>a*b
[1] 1 4 9
In addition If you want matrix multiplication it will go like...
>a%*%b
[,1]
[1,] 14
Upvotes: 2
Reputation: 4079
Agreed that this is a very basic R question, but just in case a brief "cheat sheet" is helpful to OP or some other user:
A = c(1,2,3,4,5)
B = c(2,2,2,2,2)
> A * B
[1] 2 4 6 8 10
> A + B
[1] 3 4 5 6 7
> A / B
[1] 0.5 1.0 1.5 2.0 2.5
> A - B
[1] -1 0 1 2 3
> A ^ B
[1] 1 4 9 16 25
If you wanted to multiply, say, the first integer in A and B, you could do:
A[1] * B[1]
...or any combination therein.
For multiple integers in each vector, you'd do:
A[1:2] * B[1:2]
or
A[c(1, 3)] * B[c(1, 3)]
Upvotes: 5