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

Overview

The as.numeric() function in R is used to convert a character vector into a numeric vector.

Syntax

as.numeric(x)

Parameter value

The as.numeric() function takes a single and mandatory parameter value, x, which represents the character vector to be converted.

Return value

The as.numeric() function returns a numeric vector object.

Example

# creating a character vector
x = c('1', '2', '3', '4', '5')
# implementing the as.numeric() function
y = as.numeric(x)
# printing the numeric vector
y
# checking if its a numeric matrix
is.numeric(y)

Explanation

  • Line 2: We create a variable x that contains the character vector.
  • Line 5: We implement the as.numeric() function on the x variable. The result is assigned to another variable y.
  • Line 8: We print the numeric vector y.
  • Line 11: We use the is.numeric() function to check if the variable y is numeric or not.

Free Resources