Overview of the as.numeric() Function
The as. numeric() function is part of R’s base package and is commonly used to convert objects into numeric data types. Its primary purpose is to convert factors, characters, logicals, or other data types into numeric values suitable for mathematical operations and analysis.
The basic syntax of the as. numeric() function is as follows:
Syntax: as.numeric(x)
Where, x: The object to be converted into a numeric data type.
Converting Factors to Numeric
Factors are categorical variables represented as integers with corresponding labels. The as.numeric() function converts factor levels into their underlying numeric values.
# Create a factor
factor_variable <- factor(c("Low", "Medium", "High", "Low", "High"))
# Convert factor to numeric
numeric_values <- as.numeric(factor_variable)
numeric_values
Output:
[1] 2 3 1 2 1
Converting Characters to Numeric
Characters represent text data in R. When converting characters to numeric, R attempts to interpret the character strings as numbers.
# Create a character vector
character_vector <- c("10", "20", "30", "40", "50")
# Convert character to numeric
numeric_values <- as.numeric(character_vector)
numeric_values
Output:
[1] 10 20 30 40 50
Handling Missing Values
The as.numeric() function handles missing values (NA) by converting them to NA in the resulting numeric vector. It is essential to handle missing values appropriately in data analysis.
# Create a character vector with missing values
character_vector <- c("10", "20", NA, "40", "50")
# Convert character to numeric
numeric_values <- as.numeric(character_vector)
numeric_values
Output:
[1] 10 20 NA 40 50
as.numeric()
function with base R plotting
# Create a vector of character data representing numbers
char_vector <- c("1", "3", "5", "7", "9")
# Convert the character vector to numeric
num_vector <- as.numeric(char_vector)
# Print the numeric vector to verify the conversion
print(num_vector)
# Create a basic plot of the numeric vector
plot(num_vector,
type = "o", # Line and point
col = "blue",
main = "Basic Plot of Numeric Vector",
xlab = "Index",
ylab = "Value")
Output:
as.numeric() Function in R
The as.numeric() function in R is a crucial tool for data manipulation, allowing users to convert data into numeric form, which is essential for performing mathematical operations and statistical analysis.