§2024-12-04
¶Numbers in R can be divided into 3 different categories:
- Numeric: It represents both whole and floating-point numbers. For example, 123, 32.43, etc.
- Integer: It represents only whole numbers and is denoted by L. For example, 23L, 39L, etc.
- Complex: It represents complex numbers with imaginary parts. The imaginary parts are denoted by i. For example, 2 + 3i, 5i, etc.
In R, the Numeric and Integer types both represent numbers, but they differ in terms of their storage and precision.
-
Numeric:
Type: Represents floating-point numbers, i.e., numbers that can have decimals.
Storage: It uses double-precision (64-bit) to store numbers, which allows it to store both large and small numbers with decimal points.
Default: By default, when you create a number without specifying it as an integer, R treats it as a Numeric (i.e., double).
Example:
num1 <- 3.14 # This is a Numeric num2 <- 2 # This is also treated as Numeric (double) by default
You can confirm that a value is numeric using:
is.numeric(num1) # Returns TRUE
-
Integer:
Type: Represents whole numbers (without decimals).
Storage: Integers are stored as 32-bit signed integers.
Specific Declaration: To explicitly create an Integer, you need to append an L to the number.
Example:
int1 <- 5L # This is an Integer
You can confirm that a value is an integer using:
is.integer(int1) # Returns TRUE
¶Key Differences:
- Default type: In R, any number without a decimal point is treated as a Numeric (double) by default. To create an integer, you must explicitly add an L (e.g., 5L).
- Precision: Numeric values can store decimal points and are more precise (since they use double-precision), whereas Integers are limited to whole numbers.
- Range: Integers have a smaller range compared to Numeric (due to the 32-bit storage for integers vs. 64-bit for Numerics). Therefore, Numerics can handle larger and more precise numbers.
Example:
Numeric example
num <- 10.5 is.numeric(num) # TRUE is.integer(num) # FALSE
Integer example
int <- 10L is.numeric(int) # TRUE (but it's treated as Integer) is.integer(int) # TRUE
¶Performance Consideration:
- Memory Usage: Integers take up less memory (4 bytes) compared to Numerics (8 bytes).
- Calculation Efficiency: Operations on integers are often faster than on numeric (floating-point) values, but they are limited to whole numbers.