What are the different number types and their conversions in R?

Overview

In the R programming language, there are three different types of numbers:

  1. The numeric type
  2. The integer type
  3. The complex type

Let’s take a closer look at each of the number types listed above:

Note: When we use the class() function in R, we can check the data type of a number or a variable.

The numeric type

The numeric data type contains any number, whether decimal, positive, or negative. Some examples of the numeric data type are: 1.2, 12, 1000, and -1.5.

a <- -1.5
b <- 1
c <- 1000
d <- 10.5
# to check for their data types
class(a)
class(b)
class(c)
class(d)

The integer type

The integer data type contains either positive or negative numbers without decimals. We add L after the integer value to create an integer type. Examples of the integer data type are -10L and 200L.

a <- -10L
b <- -200L
c <- 20L
# to check their data types
class(a)
class(b)
class(c)

Note: The L after the integer tells R to store the value as an integer.

The complex type

The complex data type contains parts of a real and imaginary number. Examples of the complex data type are 1-2i and 3 + 15i. The part with the “i” is the imaginary part.

a <- 1-2i
b <- 3 + 15i
# to check their data types
class(a)
class(b)

Conversion from one type to another

We can convert an integer type to a numeric type and vice-versa by adding as. to the name of the number type we want to convert to:

For example, look at the code below:

# this is a numeric type
a <- 10
# to convert the numeric data type to an integer type
x <- as.integer(a)

Explanation

To convert a to an integer variable, we create a new variable, x, and the new data type (integer) inside it, by using as.integer(a). The as.integer(a) is used to tell R to convert a to an integer.

a <- 10 # this is a numeric data type
b <- 2L # this is an integer type
# to convert from numeric to integer .
x <- as.integer(a)
# to convert from integer to numeric
y <- as.numeric(b)
# let us see if we have actually converted them
x
y
# now lets check their new data type
class(x)
class(y)

Free Resources