0
0
R-programmingHow-ToBeginner ยท 3 min read

How to Use as.numeric in R: Convert Data to Numbers Easily

In R, use as.numeric() to convert data like characters or factors into numeric values. It takes an input vector and returns a numeric vector, turning strings of numbers into actual numbers.
๐Ÿ“

Syntax

The basic syntax of as.numeric() is simple:

  • as.numeric(x): Converts x to numeric type.

Here, x can be a vector, factor, or other data types that can be interpreted as numbers.

r
as.numeric(x)
๐Ÿ’ป

Example

This example shows how to convert a character vector and a factor to numeric values using as.numeric().

r
char_vec <- c("10", "20", "30")
factor_vec <- factor(c("1", "2", "3"))

num_from_char <- as.numeric(char_vec)
num_from_factor <- as.numeric(as.character(factor_vec))

num_from_char
num_from_factor
Output
[1] 10 20 30 [1] 1 2 3
โš ๏ธ

Common Pitfalls

One common mistake is converting factors directly to numeric, which returns the underlying integer codes, not the actual numbers represented by the factor labels.

To get correct numeric values from factors, first convert to character, then to numeric.

r
factor_vec <- factor(c("10", "20", "30"))

# Wrong way: converts to integer codes
wrong_numeric <- as.numeric(factor_vec)

# Right way: convert to character first
right_numeric <- as.numeric(as.character(factor_vec))

wrong_numeric
right_numeric
Output
[1] 1 2 3 [1] 10 20 30
๐Ÿ“Š

Quick Reference

Tips for using as.numeric():

  • Use it to convert characters or factors to numbers.
  • Convert factors to character first to avoid unexpected results.
  • Non-numeric strings convert to NA with a warning.
โœ…

Key Takeaways

Use as.numeric() to convert data to numeric type in R.
Convert factors to character before numeric to get correct values.
Non-numeric strings become NA with a warning when converted.
Always check your data type after conversion to avoid surprises.