R Data Types

R Data types represent the various data types that R can handle and work with. In this guide, we will gain a strong understanding of data types within R. We will also use the typeof() function to confirm each data type.

Data Types in R

Data Types in R
Types of Data Types in R

There are six types of data types we can use with R:

Characters

Texts or string values are known as Characters, such as ‘a’ or ‘Ryan.’ To create a variable of a data type character, we must put our value in quotation marks. Anything between quotes in R will be treated as a character. For example, typing the number 1 surrounded by quotes makes it a character. We can use single or double quotes to enter data, but not both simultaneously.

> x <- 'Hello World!'
> print(typeof(x))
[1] "character"

Numeric

Numeric or double are real numbers such as 1 or decimals such as 56.34. Numbers in R are, by default, stored as double. For example, buying 2 apples at $2.3 with each result in a variable of type double:

> apple_quantity <- 2
> apple_rate <- 2.3
> print(typeof(apple_quantity))
[1] "double"
> print(typeof(apple_rate))
[1] "double"

Integers

Integers are a simplified version of double. Using integers, we can only store whole numbers without decimal components. We define integers in R using the capital letter L suffix, such as 3L or 8L. Without the capital letter L, R will store the number as a double instead.

> x <- 87L
> print(typeof(x))
[1] "integer"

Logical

Logical (Booleans) data types are binary data that contain only true or false. The primary application of this data tests the result in yes or no answers. Boolean values don’t have to be surrounded by quotes but must be written in all caps. An equivalent way of writing this is using the shorthand version, such as F for False and T for True.

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

Complex

Complex data stores imaginary values, such as 1+2i. Here, 1 represents the real part of the number, and 6 illustrates the imaginary term.

> x <- 1+2i
> print(typeof(x))
[1] "complex"

Raw

We must use the raw() function to create one. As a result of calling this function, we get the raw bytes of data. Raw data type is used for text encoding and conversion.

> x <- raw(10)
> print(typeof(x))
[1] "raw"

Leave a Comment