In R, converting a value to a number is done with as.numeric(), which returns a numeric (double) vector. You enter a character, factor, or logical vector, and you get back a numeric vector where each element is converted according to R’s coercion rules.
Formula
The conversion follows R’s internal coercion: as.numeric(x) attempts to parse each element of x as a double-precision floating-point number. For character strings, it uses the same parsing as as.double(); for factors, it converts to the underlying integer codes (not the labels) unless you first convert to character. For logical values, TRUE becomes 1 and FALSE becomes 0. The result is a numeric vector of the same length as x.
Worked Example
Using the default input "42" (a character string):
- Input:
x = "42" - R parses the string “42” as a number, yielding 42.
as.numeric("42")returns42(numeric).is.numeric(42)returnsTRUE.
So the result is 42 with is.numeric equal to TRUE.
Assumptions
- The input is a scalar or vector; the conversion is element-wise.
- For factors, the conversion uses the integer codes (1, 2, …) unless you convert to character first.
- Non-numeric strings (e.g., “abc”) produce
NAwith a warning. - R uses double-precision floating point, so very large integers may lose precision.
Why Convert to Numeric in R?
R often stores data as character or factor when reading from CSV files or spreadsheets, even when the values are numbers. For example, a column with values “1,234” or “3.14” may be read as character because of commas or leading zeros. Converting to numeric lets you perform arithmetic, statistical tests, and plotting. Also, logical values are sometimes stored as character “TRUE”/”FALSE”; converting them to numeric (0/1) is useful for regression models.
How to Convert Different Types
- Character to numeric:
as.numeric("3.14")returns 3.14. If the string has commas or spaces, remove them first (e.g.,as.numeric(gsub(",", "", "1,234"))). - Factor to numeric: Direct
as.numeric(factor)gives the internal codes (e.g., a factor with levels “low”, “medium”, “high” becomes 1, 2, 3). To get the actual numeric labels, useas.numeric(as.character(factor)). - Logical to numeric:
as.numeric(TRUE)returns 1,as.numeric(FALSE)returns 0. - Data frame columns: Use
df$col <- as.numeric(df$col)ordf[, "col"] <- as.numeric(df[, "col"]).
Common Mistakes and Pitfalls
- Factor codes vs labels: Many users expect
as.numeric(factor)to give the label values, but it gives the integer codes. Always convert to character first if the labels are numeric. - Commas and symbols: Strings like "1,000" or "$5" will produce
NAunless cleaned. Usegsub()to remove commas, dollar signs, or percent signs. - NA introduction: If any element cannot be converted, the whole vector is returned with
NAfor those elements, and a warning is issued. Check withis.na()after conversion. - Precision: R's numeric type is double-precision, so integers beyond 2^53 (about 9e15) may lose exactness. For IDs, consider keeping them as character.
Alternatives and Related Functions
as.double()is identical toas.numeric()for most purposes.as.integer()truncates decimals (e.g.,as.integer(3.9)gives 3).type.convert()automatically converts columns when reading data, respecting stringsAsFactors.readr::parse_number()from the readr package extracts numbers from strings, ignoring non-numeric characters.strtoi()converts strings to integers, but only for base-10 or other bases.
Frequently Asked Questions
Why does as.numeric(factor) give numbers like 1, 2, 3 instead of the labels?
Factors are stored internally as integers with a levels attribute. as.numeric() extracts those integers. To get the label values, first convert to character: as.numeric(as.character(f)).
How do I convert a column with commas (e.g., "1,234") to numeric?
Remove the commas first: as.numeric(gsub(",", "", df$col)). For more complex patterns, use readr::parse_number() which handles commas and other symbols.
What happens if the string is not a number?
R returns NA for that element and issues a warning like "NAs introduced by coercion". You can suppress the warning with suppressWarnings() if you expect some NAs.
Can I convert a whole data frame to numeric?
Yes, but only if all columns are convertible. Use df[] <- lapply(df, as.numeric). If some columns are character with non-numeric text, you'll get NAs.
Is as.numeric() the same as as.double()?
Yes, they are identical in R. Both convert to double-precision numeric.
Why does as.numeric("3.14") work but as.numeric("3,14") doesn't?
R expects a dot as the decimal separator. For European decimal commas, replace them with dots: as.numeric(gsub(",", ".", "3,14")).
Related
Formula used
in x | Value to convert (e.g., "42", factor "3.14") | - | "42" | 0 out n | Numeric result | - | as.numeric(x) | 6 out is_num | Is numeric? | - | is.numeric(n) | 0
Each line is one input (in, sel, list) or one result (out: label, unit, formula, decimals). How the calculators work
Method: the standard formula for this calculation with the constants and conversion factors written on the page, rounded as each result states. See method and constants, the disclaimer or report an error.
More in this section
- Mean and Median Calculation Example
- Right Triangle Trigonometry Angle Calculation
- Simple Interest Rate Calculation Example$150.00
- Mean Absolute Deviation Calculation Example
- Ladder Height Calculation Problem?24.74 ft
- Average Speed Calculation Problem?100.00 km