Trusted answers to developer questions

Onyejiaku Theophilus Chidalu

In the `R`

programming language, there are three different types of numbers:

- The
`numeric`

type - The
`integer`

type - 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.

`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.5 b <- 1 c <- 1000 d <- 10.5 # to check for their data types class(a) class(b) class(c) class(d)

Checking the data types of numeric numbers

`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 <- -10L b <- -200L c <- 20L # to check their data types class(a) class(b) class(c)

Checking the data type of integer numbers

Note: The

`L`

after the integer tells`R`

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-2i b <- 3 + 15i # to check their data types class(a) class(b)

Checking the data type of complex numbers

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 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)

Converting variables of one type into another

RELATED TAGS

communitycreator

r

CONTRIBUTOR

Onyejiaku Theophilus Chidalu

RELATED COURSES

View all Courses

Keep Exploring

Related Courses