Page Content

Tutorials

Basic Arithmetic Operators in R Programming with Example

Arithmetic Operators in R

Learning basic arithmetic in R Programming is essential for data analysis and statistical computation. R can execute commands put directly into the R terminal at the prompt, usually a > symbol, as a powerful calculator. R evaluates and displays the expression when you press Enter. R’s standard operators include addition, subtraction, multiplication, division, and exponentiation. R is vectorized, therefore these operators can be applied element-wise to vectors, which are ordered collections of values.

Addition (+)

Addition in R is done via the + operator, which is both simple and powerful in vectorized operations. R may be used like a calculator, evaluating equations like 2 + 2 at the command prompt and printing the answer to the console. In complex equations like 2 * 100/(4 + 2), parentheses () are used to specify priorities and follow the normal mathematical order of operations (PEMDAS). To use the result of an addition operation later, assign it to an object or variable, such as x <- 2 * 5^2 or c = a + b.

The addition operator in R is vectorized, so it may be applied element-wise to vectors, which is essential for efficient coding. R lines up and adds the elements of two vectors of the same length to create a new vector. For instance, c(1,2,4) + c(5,0,-1) = c(6, 2, 3). This element-wise behavior applies to matrices and data frames, where you can combine columns. R recycles unequal-length vectors while adding. After recycling the shorter vector until it is as long as the longer vector, element-wise addition is done. For instance, die + 1:2 (1:6) yields 1:6 + c(1,2,1,2,1,2). R will calculate but alert if the longer vector’s length is not a multiple of the shorter one.

Example:

# Simple addition
2 + 2

# Using parentheses (order of operations: PEMDAS)
2 * 100 / (4 + 2)

# Assigning results to variables
a <- 10
b <- 5
c <- a + b
c

# Vectorized addition (same length)
c(1, 2, 4) + c(5, 0, -1)

# Vector recycling (shorter vector is repeated)
1:6 + 1:2

Output:

[1] 4
[1] 33.33333
[1] 15
[1] 6 2 3
[1] 2 4 4 6 6 8

Subtraction (-)

The usual arithmetic operator for subtraction in R is -. Typing 4 – 1 into the console and clicking Enter returns 3 in R’s basic calculator mode. Simple subtraction instructions can be evaluated and displayed or part of assignments that store the result in a variable.

The vectorized subtraction operator in R performs element-wise operations on vectors, matrices, and arrays, making it a powerful tool. R pairs and subtracts individual items from two vectors of the same length. Subtracting c(4,11,0,8,1,2) from c(3,8,4,5,0,11) gets (-1, -3, 4, -3, -1, 9). Statistical tasks like calculating the difference between two data sets or updating values in a loop benefit from element-wise execution.

R recycles vectors with uneven lengths in subtraction. Repeating small vector elements lengthens it to match the longer vector. Subtracting a single number (scalar) from every vector element is extremely handy. For example, die – 1 subtracts 1 from each element of a vector 1:6, resulting in 0 1 2 3 4 5. R will warn if the longer vector is not a multiple of the shorter one. Many statistical procedures in R depend on vectorized behavior, such as finding the departure of each data point from the mean (e.g., x – mean(x)), calculating time series data differences, or computing residuals by subtracting projected values from actual values.

Multiplication (*)

One essential arithmetic operator for computations in R programming is the multiplication operator *. One important feature of this operator is that, unlike typical mathematics matrix multiplication, it applies to vectors or matrices and conducts element-wise multiplication. R lines up two vectors of the same length and multiplies their corresponding elements the first element of one vector by the first of the other, the second by the second, and so on in a procedure called element-wise execution.

For instance, using die * die to multiply a vector that represents a standard die, die <- 1:6, by itself yields a new vector with each element squared: 1 4 9 16 25 36. The %*% operator must be used if you plan to do matrix multiplication in linear algebra. Scalar multiplication, in which a single number is multiplied by each element of a vector or matrix, is also handled by the * operator. When two vectors of different lengths are multiplied, the shorter one is repeated until it equals the length of the longer vector before the element-wise operation starts. This is an example of R’s recycling mechanism in action.

Division (/)

R divides using the forward slash / operator. Type division expressions into the R console to use R as a powerful calculator. R evaluates and prints the result. R follows PEMDAS, which orders division and multiplication before addition and subtraction. Use parenthesis to organize calculations. Due to the parenthesis’ first operation, 6 / (4 – 1) will be evaluated as 6 / 3, producing 2. 2 * 100/(4 + 2) yields 33.33, while 2 * 100/4 + 2 yields 52 since division precedes addition.

Vectorized arithmetic operators, including division, are essential to R. When you divide two vectors of the same length using the / operator, element-wise division occurs. To create a new vector from a vector die <-1:6, use the die / 2 command to divide each element by 2. 0.5 1.0 1.5 2.0 2.5 3.0. Vector recycling is used by R to divide unequal-length vectors. The shorter vector’s elements are repeated until it matches the longer vector’s length, then element-wise division begins. R will conduct the operation but raise a warning if the longer vector’s length is not an even multiple of the shorter vector’s length. This recycling rule is often used to divide a vector by a scalar.

R also determines special division outcomes. Inf is infinite when divided by zero, such as 1/0 or 59/0. Undefined operations like 0/0 yield NaN, or “Not a Number”.

Exponents (^)

The R programming language uses the ^ operator for exponentiation. R functions as a powerful calculator, allowing you to directly write expressions like 2^10 into the terminal, resulting in 1024. Similarly, 3^2 yields 9. Due to the exponent operator’s precedence, operation order is crucial. Exponents in arithmetic calculations must be surrounded in parenthesis, such as 2^(2+1).

Vectorization is an important element of R’s arithmetic operators, such as ^. This allows element-wise action on an entire vector. The command x^2 squares each element of a vector c(1, -1, 3.5, 2), resulting in a new vector (1.00, 1.00, 12.25, 4.00). Statistics benefits greatly from vectorization, enabling straightforward, short code like 2^(0:10) for generating powers of 2. The ^ operator is commonly used in built-in and user-defined function bodies.

It can be used in a for loop to calculate squares (e.g., i^2) or to implement mathematical formulas in functions (e.g., x^y). Statistical modeling requires it, such as fitting polynomial regression models with formulas like y ~ x + I(x^2) or changing reward values in simulations with expressions like prize * 2 ^ diamonds.

Other Useful Arithmetic Operators

R offers specific arithmetic operators for integer and matrix algebra in addition to the basic addition, subtraction, multiplication, division, and exponent operators. R has integer division and modulo operators for integer calculations. The modulo operator returns the remainder, while integer division returns the integer component. The integer quotient of y divided by x is y %/% x, while the remainder is y %% x. Programmers can use the modulo operator to check if a number is odd using n %% 2 == 1.

R also has specific operators for classical matrix multiplication, unlike element-wise operations. Inner matrix multiplication is possible with the %*% operator, unlike the * operator. For outer multiplication, use %o%. The colon operator (:) constructs a vector of integers between two specified numbers, such as 1:10. Colon operator precedence is higher than conventional arithmetic operators.

Order of Operations and Use of Parentheses

R programming evaluates complex expression operators in a normal mathematical order. The order operators by precedence: exponentiation (^), unary minus and plus, multiplication (*), division (/), modulus (%), and addition (+) and subtraction (-). Following arithmetic operators, R evaluates relational operators (==, >, <) and logical operators, with AND (&, &&) taking precedence over OR (|, ||). In R, operators of the same precedence are evaluated left to right. The colon operator (:) has a higher precedence than arithmetic operators; for example, 1:10-1 is interpreted as (1:10) – 1 since 1:10 is formed before 1 is subtracted from each element.


Use parentheses () to group operations to change this default order. The stress that parentheses are always examined first, making them crucial for accurate computations. The instruction 2 * 100/4 + 2 yields 52 because multiplication and division precede addition. However, employing parenthesis in 6 / (4 – 1) or 2 * 100/(4 + 2) computes 4 – 1 and 4 + 2 first, yielding 2 and 33.33, respectively. When nested functions are linked, as round(mean(die)), R resolves the expression from inner to outer. Separate parentheses () for arithmetic priorities from function calls (e.g., q() or mean(x)) and braces {} for grouping commands, such as in function bodies or if statements.

Arithmetic with Special Values

R’s special values for mathematical ideas must be understood in arithmetic.

NA (Not Available): The R letter NA stands for “Not Available” and is used to represent missing data or values. NA is a reserved R word. Due to their effects on calculations and data processing, R’s handling of missing values is crucial. Mathematical or logical operations with NA propagate to NA.

Inf (Infinity): In R, Inf is a reserved term for infinity. When a calculation yields a mathematically infinite or too large for R value, this value is employed. Two main methods generate Inf. It happens when a number exceeds the computer’s largest representable real number, stored in.Machine$double.xmax. A huge calculation like 2^2000 will result in Inf. Zero division is the second cause. Any non-zero number divided by zero yields Inf or -Inf, depending on numerator sign. 59/0 and -59/0 give Inf and -Inf, respectively.

NaN (Not a Number): NaN, which means “Not a Number” in R, is a reserved word for undefined or impossible mathematical operations. It is different from NA (Not Available), which is used for missing data, however R may treat them similarly. NaN is usually produced by dividing zero by zero (0/0), subtracting infinity from infinity (Inf – Inf), multiplying zero by infinity (0*Inf), or taking the logarithm of a negative number. It may appear in statistical function output when calculations are impossible.

Vectorization, recycling, and the logical handling of special values are necessary for data processing and analysis, and R’s capabilities go beyond a calculator.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index