0
0
R Programmingprogramming~5 mins

Vector arithmetic (element-wise) in R Programming

Choose your learning style9 modes available
Introduction

Vector arithmetic lets you do math on lists of numbers all at once, making calculations faster and easier.

Adding daily temperatures from two different cities to compare combined heat.
Calculating total sales by adding sales numbers from two different stores.
Subtracting expenses from income for multiple months to find monthly profit.
Multiplying quantities and prices to find total cost for several items.
Dividing total distance by time for multiple trips to find speeds.
Syntax
R Programming
result <- vector1 + vector2
result <- vector1 - vector2
result <- vector1 * vector2
result <- vector1 / vector2

Vectors must be the same length or R will recycle elements, which can cause unexpected results.

Operations are done element by element, like adding each pair of numbers from the two vectors.

Examples
Adds each element: 1+4, 2+5, 3+6 resulting in c(5, 7, 9).
R Programming
a <- c(1, 2, 3)
b <- c(4, 5, 6)
sum <- a + b
Subtracts each element: 10-1, 20-2, 30-3 resulting in c(9, 18, 27).
R Programming
a <- c(10, 20, 30)
b <- c(1, 2, 3)
diff <- a - b
Multiplies each element: 2*3, 4*5, 6*7 resulting in c(6, 20, 42).
R Programming
a <- c(2, 4, 6)
b <- c(3, 5, 7)
product <- a * b
Divides each element: 8/2, 16/4, 24/8 resulting in c(4, 4, 3).
R Programming
a <- c(8, 16, 24)
b <- c(2, 4, 8)
quotient <- a / b
Sample Program

This program adds temperatures from two cities day by day to find the combined temperature.

R Programming
temps_city1 <- c(20, 22, 19, 24)
temps_city2 <- c(18, 21, 20, 23)
total_temps <- temps_city1 + temps_city2
print(total_temps)
OutputSuccess
Important Notes

If vectors have different lengths, R repeats the shorter one to match the longer, which can cause mistakes.

Use functions like length() to check vector sizes before doing arithmetic.

Summary

Vector arithmetic applies math operations to each pair of elements in two vectors.

Vectors should be the same length to avoid unexpected recycling.

This makes working with lists of numbers easy and fast.