Numbers in R can be divided into 3 different categories:
- Numeric: It represents both whole and floating-point numbers. For example, 123, 32.43, etc.
- Integer: It represents only whole numbers and is denoted by
L. For example, 23L, 39L, etc.
- Complex: It represents complex numbers with imaginary parts. The imaginary parts are denoted by
i. For example, 2 + 3i, 5i, etc.
Numeric Data Type
Numeric data type is the most frequently used data type in R. It is the default data type whenever you declare a variable with numbers.
You can store any type of number (with or without decimal) in a variable with
numeric data type. For example,
# decimal variablemy_decimal <- 123.45print(class(my_decimal)) # variable without decimalmy_number <- 34print(class(my_number))
 "numeric"  "numeric"
Here, both the my_decimal and my_number variables are of
Integer Data Type
Integers are a type of numeric data that can take values without decimal. It's mostly used when you are sure that the variable can not have any decimal values in the future.
In order to create an
integer variable, you must use the suffix
L at the end of the value. For example,
my_integer <- 123L# print the value of my_integer print(my_integer) # print the data type of my_integer print(class(my_integer))
 123  "integer"
Here, the variable my_integer contains the value
123L. The suffix
L at the end of the value indicates that my_integer is of
Complex Data Type
In R, variables with complex data types contain values with an imaginary part. This can be indicated by using the
i as a suffix. For example,
# variable with only imaginary partz1 <- 5iprint(z1) print(class(z1)) # variable with both real and imaginary partsz2 <- 3 + 3iprint(z2) print(class(z2))
 0+5i  "complex"  3+3i  "complex"
Here, the variables z1 and z2 have been declared as
complex data types with an imaginary part denoted by the suffix
Frequently Asked Questions
In R, we use the
as.numeric() function to convert any number to
numeric value. For example,
# integer variable a <- 4L print(class(a)) # complex variable b <- 1 + 2i print(class(b))# convert from integer to numeric x <- as.numeric(a)print(class(x))# convert from complex to numeric y <- as.numeric(b)print(class(y))
 "integer"  "complex"  "numeric"  "numeric" Warning message: imaginary parts discarded in coercion
Here, you can see that while converting the
complex number to a
numeric value, the imaginary parts are discarded.
You can use the
as.complex() function to convert any number to a
complex value. For example,
# integer variable a <- 4L print(class(a)) # numeric variable b <- 23 print(class(b))# convert from integer to complex y <- as.complex(a)print(class(y))# convert from numeric to complex z <- as.complex(b)print(class(z))
 "integer"  "numeric"  "complex"  "complex"