R as a Calculator

In the Windows Operating system, The R installer will have created an icon for R on the desktop and a Start Menu item. Double-click the R icon to start the R Program; R will open the console, to type R commands. In this post, we will learn how to use R Language as a Calculator.

The greater than sing (>) in the console is the prompt symbol. In this tutorial, we will use the R language as a calculator (we will be Using R for the computation of mathematical expressions), by typing some simple mathematical expressions at the prompt (>). Anything that can be computed on a pocket calculator can also be computed at the R prompt. After entering the expression on the prompt, you have to press the Enter key from the keyboard to execute the command.

Using R Language As a Calculator

Some examples using R as a calculator are as follows

1 + 2   #add two or more numbers
1 - 2   #Substracts two or more numbers
1 * 2   #multiply two or more numbers
1 / 2   #divides two more more numbers
1 %/% 2 #gives the integer part of the quotient
2 ^ 1   #gives exponentiation
31 %% 7 #gives the remainder after division

These operators also work fine for complex numbers.

Upon pressing the enter key, the result of the expression will appear, prefixed by a number in a square bracket:

1 + 2

# output
[1] 54

The [1] indicates that this is the first result from the command.

One can also use R as an advanced scientific calculator. Some advanced calculations that are available in scientific calculators can also be easily done in R for example,

sqrt(5)      #Square Root of a number
log(10)      #Natural log of a number
sin(45)      #Trignometric function (sin function)
pi           #pi value 3.141593
exp(2)       #Antilog, e raised to a power
log10(5)     #Log of a number base 10
factorial(5) #Factorial of a number e.g 5!
abs(1/-2)    #Absolute values of a number 
2*pi/360     #Number of radian in one Babylonian degree of a circle

Remember R prints all very large or very small numbers in scientific notation.

R as a Calculator

Order of Precedence/ Operations

The R language also makes use of parentheses for grouping operations to follow the rules for the order of operations. for example

1 - 2/3   #It first computes 2/3 and then subtracts it from 1
(1-2)/3   #It first computes (1-2) and then divides it by 3

The R Language recognizes certain goofs, like trying to divide by zero, missing values in data, etc.

1/0       # Undefined, R tells it an infinity (Inf)
0/0       # Not a number (NaN) 
"one"/2   # Strings or characters is divided by a number

Further Reading: Computing Descriptive Statistics in R

Online MCQs Computer Science with Answers

Leave a Reply