In the R
programming language, there are three different types of numbers:
numeric
typeinteger
typecomplex
typeLet’s take a closer look at each of the number types listed above:
Note: When we use the
class()
function inR
, we can check the data type of a number or a variable.
numeric
typeThe 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.5b <- 1c <- 1000d <- 10.5# to check for their data typesclass(a)class(b)class(c)class(d)
integer
typeThe 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 <- -10Lb <- -200Lc <- 20L# to check their data typesclass(a)class(b)class(c)
Note: The
L
after the integer tellsR
to store the value as an integer.
complex
typeThe 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-2ib <- 3 + 15i# to check their data typesclass(a)class(b)
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)
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 typeb <- 2L # this is an integer type# to convert from numeric to integer .x <- as.integer(a)# to convert from integer to numericy <- as.numeric(b)# let us see if we have actually converted themxy# now lets check their new data typeclass(x)class(y)