The as.numeric() function in R programming language is used to convert an object into a numeric type. It is commonly used when data is in character or factor format but needs to be treated as numbers for analysis. This function is part of base R and is useful for data cleaning and preparation.
Syntax:
as.numeric(x)
Parameters:
x: The object we want to convert to numeric.
1. Converting Factors to Numeric
We create a factor variable and convert it into its corresponding numeric codes.
- factor(): Creates a factor variable (categorical variable).
- as.numeric(): Converts the factor into its underlying numeric codes.
factor_variable <- factor(c("Low", "Medium", "High", "Low", "High"))
numeric_values <- as.numeric(factor_variable)
numeric_values
Output:
[1] 2 3 1 2 1
2. Converting Characters to Numeric
We define a character vector with numeric-like strings and convert it into numeric values.
- c(): Combines values into a vector.
- as.numeric(): Converts character strings to actual numbers.
character_vector <- c("10", "20", "30", "40", "50")
numeric_values <- as.numeric(character_vector)
numeric_values
Output:
[1] 10 20 30 40 50
3. Handling Missing Values
We include a missing value in the vector and convert it to numeric while preserving the missing value.
- NA: Represents missing data in R.
- as.numeric(): Keeps
NAasNAafter conversion.
character_vector <- c("10", "20", NA, "40", "50")
numeric_values <- as.numeric(character_vector)
numeric_values
Output:
[1] 10 20 NA 40 50
4. Using as.numeric() with Base R Plotting
We convert a character vector into numeric values and then plot it using basic R plotting.
- as.numeric(): Converts character data to numeric.
- plot(): Draws a graph using the numeric vector.
- type = "o": Displays both lines and points.
- col: Sets the color of the line.
- main: Sets the title of the plot.
- xlab: Sets the x-axis label.
- ylab: Sets the y-axis label.
char_vector <- c("1", "3", "5", "7", "9")
num_vector <- as.numeric(char_vector)
print(num_vector)
plot(num_vector,
type = "o",
col = "blue",
main = "Basic Plot of Numeric Vector",
xlab = "Index",
ylab = "Value")
Output:

The as.numeric() function is useful for converting factors, characters and logical values into numeric form in R. It is often used when cleaning data, preparing it for analysis or creating visualizations.