6  Data Types

Data is stored differently depending on what it represents when programming. For example, a number is going to be stored as a different data type than a letter is.

There are five basic data types in R that each store a single value:

In addition, each missing values can be specified with the special NA type, which can represent each of the data types listed above.

6.1 Numeric

6.1.1 Double

Let’s explore the “double” data type by assigning a number to a variable and then check its type by using the “typeof” function. Alternatively, we can use the “is.double” function to check whether or not the variable is a double.

x <- 6.2
typeof(x)
[1] "double"
is.double(x)
[1] TRUE

Next, let’s check whether or not the variable is numeric by using the “is.numeric” function.

is.numeric(x)
[1] TRUE

This function should return “TRUE” as well, which demonstrates the fact that a double is a subset of the numeric data type.

6.1.2 Integer

Let’s explore the “integer” data type by assigning a whole number followed by the capital letter “L” to a variable and then check its type by using the “typeof” function. Alternatively, we can use the “is.integer” function to check whether or not the variable is an integer.

x <- 6L
# By using the "typeof" function, we can check the data type of x
typeof(x)
[1] "integer"
is.integer(x)
[1] TRUE

Next, let’s check whether or not the variable is numeric by using the “is.numeric” function.

is.numeric(x)
[1] TRUE

This function should return “TRUE” as well, demonstrating that an integer is also a subset of the numeric data type.

6.2 Complex

Complex data types make use of the mathematical concept of an imaginary number through the use of the lowercase letter “i”. The following example sets “x” equal to six times i and then displays the type of x.

x <- 6i
typeof(x)
[1] "complex"

6.3 Character

Character data types store text data. When creating characters, make sure you wrap your text in quotation marks.

x <- "Hello!"
typeof(x)
[1] "character"

6.4 Logical

Logical data types store either “TRUE” or “FALSE”. Unlike characters, these data should not be wrapped in quotation marks.

x <- TRUE
typeof(x)
[1] "logical"

6.5 Raw

Used less often, the raw data type will store data as raw bytes. You can convert character data types to raw data types by using the “charToRaw” function. Similarly, you can convert integer data types to raw data types through the use of the “intToBits” function.

x <- charToRaw("Hello!")
print(x)
[1] 48 65 6c 6c 6f 21
typeof(x)
[1] "raw"
x <- intToBits(6L)
print(x)
 [1] 00 01 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[26] 00 00 00 00 00 00 00
typeof(x)
[1] "raw"

6.6 Resources