Open In App

How to Convert Character to Numeric in R?

Last Updated : 08 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to convert characters to numeric in R Programming Language.

We can convert to numeric by using as.numeric() function.

Syntax:

as.numeric(character)

where, character is an character vector

Example:

R




# create a vector with 5 characters
data = c('1', '2', '3', '4', '5')
 
# display type
class(data)
 
# convert to numeric
final = as.numeric(data)
print(final)
 
# display type
class(final)


Output:

[1] "character"
[1] 1 2 3 4 5
[1] "numeric"

Convert a column from character to numeric

Here we are considering a dataframe and then convert a dataframe column from character  to numeric.

Syntax:

as.numeric(dataframe$column_name)

Example:

R




# create a dataframe with 4 rows and 3 columns
data = data.frame(marks1=c('90', '78', '89', '76'),
                  marks2=c('92', '68', '78', '96'),
                  marks3=c('90', '78', '89', '76'))
 
# convert to numeric for marks1 column
print(as.numeric(data$marks1))
 
# convert to numeric for marks2 column
print(as.numeric(data$marks2))
 
# convert to numeric for marks3 column
print(as.numeric(data$marks3))


Output:

[1] 90 78 89 76
[1] 92 68 78 96
[1] 90 78 89 76


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads