To convert a character vector to numeric in R, use the as.numeric() function. It creates or coerces objects of type “numeric”.
Syntax
num_val <- as.numeric(x)
Example 1: Converting character vector to numeric
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"
Example 2: Working non-numeric values
If the character vector contains non-numeric values, those values will be converted into NA (‘Not Available’) in the numeric vector.
# Character vector with a non-numeric value
char_vector <- c("1", "2", "three", "4", "5")
# Convert to numeric
num_vector <- as.numeric(char_vector)
# Print the numeric vector
print(num_vector)
Output
Warning message:
NAs introduced by coercion
[1] 1 2 NA 4 5
Before using this function, it’s a good practice to ensure that all elements of your character vector are numeric (or convertible to numeric).
Example 3: Converting a data frame column from a character to numeric
# Create data frame
df <- data.frame(
x = c("21", "18", "19", "22", "26"),
y = c(28, 34, 35, 36, 40)
)
# Convert column 'a' from character to numeric
df$x <- as.numeric(df$x)
# View new data frame
df
Output
x y
1 21 28
2 18 34
3 19 35
4 22 36
5 26 40
Example 4: Converting all characters of a data frame to numeric
# Create data frame
df <- data.frame(
x = c("21", "18", "19", "22", "26"),
y = c(28, 34, 35, 36, 40),
z = as.factor(c(1, 2, 3, 4, 5)),
d = c(11, 12, 13, 14, 15),
stringsAsFactors = FALSE
)
sapply(df, class)
data_num <- as.data.frame(apply(df, 2, as.numeric))
sapply(data_num, class)
Output
Example 5: Checking if a variable is numeric
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.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.