# How to do Vector Arithmetic in R?

## Problem –

You want to operate on an entire vector at once.

## Solution –

The usual arithmetic operators can perform element-wise operations on entire vectors.

Let’s say we have two vectors.

> a <- c(5, 10, 15, 20, 25)
> b <- c(2, 4, 6, 8, 10)

Now, we can perform various arithmetic operations on them.

> a + b
[1]  7 14 21 28 35
> a - b
[1]  3  6  9 12 15
> a * b
[1]  10  40  90 160 250
> a / b
[1] 2.5 2.5 2.5 2.5 2.5

You can also perform vector arithmetic with a scalar.

> a + 2
[1]  7 12 17 22 27
> a - 2
[1]  3  8 13 18 23
> a * 2
[1] 10 20 30 40 50
> a / 2
[1]  2.5  5.0  7.5 10.0 12.5

Rating: 1 out of 5.

Posted in RTagged