Home / Programs / Arithmetic operation in R
Programming Example

Arithmetic operation in R

👁 438 Views
💻 Practical Program
📘 Step by Step Learning
  • Type 2^5 in the editor to calculate 2 to the power 5.
  • Type 28 %% 6 to calculate 28 modulo 6.
  • Note how the # symbol is used to add comments on the R code.

Program Code

# An addition
5 + 5 

# A subtraction
5 - 5 

# A multiplication
3 * 5

 # A division
(5 + 5) / 2 

# A Exponentiation
2^5

# a Modulo
5 %% 3

# Exponentiation


# Modulo

Output

> # An addition
> 5 + 5
[1] 10
> 
> # A subtraction
> 5 - 5
[1] 0
> 
> # A multiplication
> 3 * 5
[1] 15
> 
>  # A division
> (5 + 5) / 2
[1] 5
> 
> # A Exponentiation
> 2^5
[1] 32
> 
> # a Modulo
> 5 %% 3
[1] 2
> 
> # Exponentiation
> 
> 
> # Modulo
> # An addition
> 5 + 5
[1] 10
> 
> # A subtraction
> 5 - 5
[1] 0
> 
> # A multiplication
> 3 * 5
[1] 15
> 
>  # A division
> (5 + 5) / 2
[1] 5
> 
> # A Exponentiation
> 2^5
[1] 32
> 
> # a Modulo
> 5 %% 3
[1] 2

Explanation

Arithmetic with R

In its most basic form, R can be used as a simple calculator. Consider the following arithmetic operators:

  • Addition: +
  • Subtraction: -
  • Multiplication: *
  • Division: /
  • Exponentiation: ^
  • Modulo: %%

The last two might need some explaining:

  • The ^ operator raises the number to its left to the power of the number to its right: for example 3^2 is 9.
  • The modulo returns the remainder of the division of the number to the left by the number on its right, for example 5 modulo 3 or 5 %% 3 is 2.

With this knowledge, follow the instructions below to complete the exercise.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.