How to Convert Character Vector to Numeric in R

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

Visualization of Converting Character to Numeric in R

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

Converting a Column from a character to a 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

Convert all characters of a data frame to numeric

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.

Leave a Comment