Lesson 3a - Numbers
In R, there are different “types” of data. The most basic types are called atomic data types. There are 5 atomic data types: numeric, integer, complex, character (strings), and logical (booleans).
In this lesson, we’ll be covering the numeric, integer, and complex data types. They are all different types of numbers.
Table of Contents
Lesson Objectives
- Use the
class()
function to see data types. - Explore the differences between the numeric, integer, and complex data types.
What Data Type Am I Working With?
The best way to see what type of data a variable is holding is by using the class()
function.
Input
class(5)
class(5L)
class(5 + 3i)
Output
[1] "numeric"
[1] "integer"
[1] "complex"
Numeric
The numeric type is the most common type of number. It includes all real numbers.
It’s important to note that numeric numbers are approximations (they’re only accurate to 15 decimal places), so some rounding errors may arise when comparing numbers. The example below showcases this.
Input
a <- 2
# We use == to compare two numbers. It returns TRUE if they're equal, FALSE otherwise. We talk more about this in more detail in lesson 3b.
a^2 == 2 # This *should* return TRUE because the square of square root 2 is 2.
Output
[1] FALSE
Integer
When you’re sure your data will only consist of integers, you can use the integer type. To declare a number to be an integer, add an L
at the end of the number.
a <- 2L
If you divide two integers, R will create a numeric output rather than an integer. If you meant to do integer division, you still need to use the %/% operator.
Input
class(11L / 2L) class(11L %/% 2L)
Output
[1] "numeric" [1] "integer"
Complex
R also support complex numbers.
Input
(5 + 3i) * (1i)
Output
[1] -3+5i
This website goes into greater detail about what R has to offer with complex numbers.
Key Points / Summary
- You can use the
class()
function to inspect the data type of a variable or value. - Numeric, integer, and complex numbers are the different number types R supports.
- ‘Numeric’ numbers are only approximations of decimal numbers and they can lead to rounding errors.