We can use the following syntax to convert a character vector to a numeric vector in R:
numeric_vector numeric(character_vector)
This tutorial provides several examples of how to use this function in practice.
Example 1: Convert a Vector from Character to Numeric
The following code shows how to convert a character vector to a numeric vector:
#create character vector
chars
#convert character vector to numeric vector
numbers numeric(chars)
#view numeric vector
numbers
[1] 12 14 19 22 26
#confirm class of numeric vector
class(numbers)
[1] "numeric"
Example 2: Convert a Column from Character to Numeric
The following code shows how to convert a specific column in a data frame from character to numeric:
#create data frame df frame(a = c('12', '14', '19', '22', '26'), b = c(28, 34, 35, 36, 40)) #convert column 'a' from character to numeric df$a numeric(df$a) #view new data frame df a b 1 12 28 2 14 34 3 19 35 4 22 36 5 26 40 #confirm class of numeric vector class(df$a) [1] "numeric"
Example 3: Convert Several Columns from Character to Numeric
The following code shows how to convert all character columns in a data frame from character to numeric:
#create data frame df frame(a = c('12', '14', '19', '22', '26'), b = c('28', '34', '35', '36', '40'), c = as.factor(c(1, 2, 3, 4, 5)), d = c(45, 56, 54, 57, 59)) #display classes of each column sapply(df, class) a b c d "character" "character" "factor" "numeric" #identify all character columns chars sapply(df, is.character) #convert all character columns to numeric df[ , chars] data.frame(apply(df[ , chars], 2, as.numeric)) #display classes of each column sapply(df, class) a b c d "numeric" "numeric" "factor" "numeric"
This code made the following changes to the data frame columns:
- Column a: From character to numeric
- Column b: From character to numeric
- Column c: Unchanged (since it was a factor)
- Column d: Unchanged (since it was already numeric)
By using the apply() and sapply() functions, we were able to convert only the character columns to numeric columns and leave all other columns unchanged.
Additional Resources
How to Convert Numeric to Character in R
How to Convert Character to Factor in R
How to Convert Factor to Character in R
How to Convert a Character to a Timestamp in R