Arithmetic Operators in R Programming Language: Explanation and Examples

Rumman Ansari   Software Engineer   2024-07-05 06:40:03   5974  Share
Subject Syllabus DetailsSubject Details 1 Program
☰ TContent
☰Fullscreen

Table of Content:

Arithmetic Operators

Following table shows the arithmetic operators supported by R language. The operators act on each element of the vector.

Operator Description Example
+ Adds two vectors
a <- c( 2,5.5,6)
b <- c(8, 3, 4)
print(a+b)

it produces the following result −

[1] 10.0  8.5  10.0
Subtracts second vector from the first
a <- c( 2,5.5,6)
b <- c(8, 3, 4)
print(a-b)

it produces the following result −

[1] -6.0  2.5  2.0
* Multiplies both vectors
a <- c( 2,5.5,6)
b <- c(8, 3, 4)
print(a*b)

it produces the following result −

[1] 16.0 16.5 24.0
/ Divide the first vector with the second
a <- c( 2,5.5,6)
b <- c(8, 3, 4)
print(a/b)

When we execute the above code, it produces the following result −

[1] 0.250000 1.833333 1.500000
%% Give the remainder of the first vector with the second
a <- c( 2,5.5,6)
b <- c(8, 3, 4)
print(a%%b)

it produces the following result −

[1] 2.0 2.5 2.0
%/% The result of division of first vector with second (quotient)
a <- c( 2,5.5,6)
b <- c(8, 3, 4)
print(a%/%b)

it produces the following result −

[1] 0 1 1
^ The first vector raised to the exponent of second vector
a <- c( 2,5.5,6)
b <- c(8, 3, 4)
print(a^b)

it produces the following result −

[1]  256.000  166.375 1296.000

More Examples

> x <- 5
> y <- 16
> x+y
[1] 21
> x-y
[1] -11
> x*y
[1] 80
> y/x
[1] 3.2
> y%/%x
[1] 3
> y%%x
[1] 1
> y^x
[1] 1048576