How to Convert Character to Numeric in R

Type conversions in R work as you would expect. For example, adding a character string to a numeric vector converts all the vector elements to the character. Let’s see how to convert a character vector to a numeric vector in R.

Convert Character to Numeric in R

To convert character to numeric in R, use the as.numeric() function. The as.numeric() is a built-in R function that creates or coerces objects of type “numeric”. If you want to convert a factor to numeric, use the as.numeric() function.

Code snippet

as.numeric(data)

Example

Before converting a character, let’s create a character vector, and to create a character vector, use the as.character() function.

char <- as.character(sample(c(19, 11, 46, 21), 10, replace = TRUE))
char

Output

 [1] "11" "11" "21" "11" "46" "46" "11" "21" "19" "21"

To check the data type of the output, use the typeof() function.

char <- as.character(sample(c(19, 11, 46, 21), 10, replace = TRUE))
typeof(char)

Output

[1] "character"

To convert from character to numeric data type, use the as.numeric() function.

char <- as.character(sample(c(19, 11, 46, 21), 10, replace = TRUE))
char
typeof(char)

num <- as.numeric(char)
num
typeof(num)

Output

[1] "21" "19" "46" "46" "11" "19" "21" "46" "19" "21"
[1] "character"
[1] 46 19 21 21 11 46 19 19 11 46
[1] "double"

As you can see that the data type of output variable is double. That means we successfully converted from character to double value. There is also one more method called is.numeric(), which you can use to check if any value is numeric or not.

char <- as.character(sample(c(19, 11, 46, 21), 10, replace = TRUE))
char
typeof(char)

num <- as.numeric(char)
num
is.numeric(num)

Output

[1] "11" "11" "46" "11" "11" "46" "21" "21" "46" "46"
[1] "character"
[1] 11 11 46 11 11 46 21 21 46 46
[1] TRUE

It returns TRUE, which means it is numeric.

See also

R List to Numeric

R List to JSON

R List to Array

R List to Vector

R List to Matrix

Leave a Comment