R Tutorial



R NUMBERS


Numbers in R

Numbers are one of the most basic and important data types in R. They represent numeric values and can be used for calculations, data analysis, and statistical operations.

Types of Numbers in R

  • Integer: Whole numbers without decimal points (e.g., 5, -10).
  • Numeric (Double): Numbers with decimal points (floating point), such as 3.14 or -0.5. This is the default numeric type in R.
  • Complex: Numbers with real and imaginary parts, like 3 + 2i.

Checking Number Types

You can check the type of a number using functions like typeof() or class():

x <- 10
typeof(x)     # "double" (by default numbers are double)
class(x)      # "numeric"

y <- 10L      # L suffix makes it integer
typeof(y)     # "integer"
class(y)      # "integer"

z <- 3 + 2i
typeof(z)     # "complex"
class(z)      # "complex"
  

Creating Numbers

Simply assign numbers to variables:

a <- 25          # numeric (double) by default
b <- 12L         # integer (with L suffix)
c <- 3.14159     # numeric with decimal
d <- -7.5        # negative numeric
e <- 1+4i        # complex number
  

Basic Arithmetic Operations with Numbers

Operation Symbol Example Result
Addition + 5 + 3 8
Subtraction - 5 - 3 2
Multiplication * 5 * 3 15
Division / 5 / 3 1.6667
Exponentiation ^ 5 ^ 3 125
Modulo (Remainder) %% 5 %% 3 2
Integer Division %/% 5 %/% 3 1

Example: Using Numbers in R

num1 <- 10
num2 <- 3

sum <- num1 + num2
difference <- num1 - num2
product <- num1 * num2
quotient <- num1 / num2
power <- num1 ^ num2
remainder <- num1 %% num2
int_div <- num1 %/% num2

print(paste("Sum:", sum))
print(paste("Difference:", difference))
print(paste("Product:", product))
print(paste("Quotient:", quotient))
print(paste("Power:", power))
print(paste("Remainder:", remainder))
print(paste("Integer Division:", int_div))
  

Summary

  • Numbers in R can be integers, numeric (double), or complex.
  • By default, numbers without L suffix are stored as numeric (double).
  • R supports all common arithmetic operations.
  • Use typeof() or class() to check the type of numbers.

Practice Exercise

Write a script that takes two numbers, calculates and prints:

  • Their sum, difference, product, quotient, and remainder.
  • The result of raising the first number to the power of the second number.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review