What is the as.integer() function in R?

Overview

The as.integer() function in R transforms a character object into an integer object.

Syntax

as.integer(x)

Parameter value

The as.integer() function takes a single mandatory parameter, x, representing the character object passed.

Return value

The as.integer() function returns an integer object.

Example 1

# calling the as.integer() function on character objects
as.integer("1")
as.integer("1.5")
as.integer("10")
as.integer("-10.5")
as.integer("0x290")

Code explanation

We call the as.integer() function on some given character objects in the code above. The function helps return their values as integer objects.

Example 2

# creating a vector
myvector <- c(1, 2, 3, 4, 5)
# converting the vector to integer
myinteger <- as.integer(myvector)
myinteger
# to check if it is an integer
is.integer(myinteger)

Code explanation

  • Line 2: We create a vector object myvector.
  • Line 5: We implement the as.integer() function on the vector object myvector. We assign the result to another variable, myinteger.
  • Line 6: We print the variable myinteger.
  • Line 9: To confirm if the variable myinteger is an integer object, we make use of the is.integer() function.

Free Resources