sumaafaizy - 5 months ago 62

R Question

This is for R programming. I have two vectors: numbers1 and numbers2 with integer elements in them. I want to calculate the elementwise 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.

Answer

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)]
```