Skip to main content
v2026.11,986 entries · CC-BY 4.0

as.numeric in R: Safe Numeric Conversion

Convert numeric text in R while retaining source values, spotting new missing results and checking factor codes before analysis.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

Use as.numeric(x) in R to convert numeric text to numbers. Check the result before replacing a research data column: unrecognised text can become NA, and factors return level codes. Keep the original values alongside the conversion so you can identify which rows need attention.

What it is used for in research

A measurement column can arrive from a spreadsheet or text export as character data. Explicit conversion is useful when that column should contain quantities for analysis. The R Core Team’s Numeric Vectors documentation distinguishes as.numeric(), which converts, from is.numeric(), which tests an object. A successful type test alone does not establish that the values represent the intended measurements.

This walkthrough uses an illustrative composite of sample measurements, rather than real observations. Its purpose is to preserve a visible link between each input and its converted value. The accompanying data table compiles input situations, conversion behaviour and checks from several official manuals; it is separate from the worked example. For the broader distinction between storage type and class, see R data types and coercion.

Install or access

The R Project provides R as a free environment for statistical computing and graphics, with downloads through CRAN for Windows, macOS and UNIX platforms. The conversion function belongs to base R. You do not need a separate conversion package to follow this example. Start an R session and enter the commands at its console or place them in your analysis script.

Use the official R Project download link in the Sources section when obtaining R. Within the session, help(as.numeric) opens the function’s help topic. Keep that reference beside your script when an object has a special class: the documented signature includes method arguments, and not every class should be treated as an ordinary measurement vector. This guide’s main example deliberately starts with plain character data.

as.numeric R syntax and arguments

as.numeric(x, ...)

The argument x is the object to convert. The dots allow further arguments for methods; they are not a general instruction to guess a decimal convention. For ordinary numeric text, supply the vector as x. The Numeric Vectors manual states that as.numeric() and as.double() are identical. It also distinguishes numeric() from conversion: numeric(length) creates a vector of zeros, so numeric(5) does not convert the value 5.

Step-by-step task

The following audit is an editorial workflow built from the documented conversion, structure and missing-value functions. Keep all rows while diagnosing the input. The deliberately invalid entry makes a warning useful evidence, rather than an interruption to hide.

  1. Create an illustrative composite input. Use a small example whose intended values you can inspect individually. The raw column includes whitespace, a negative number, an invalid token and an existing missing value.
measurements = data.frame(
  sample_id = c("S01", "S02", "S03", "S04", "S05"),
  raw_value = c("12.5", " 8.0 ", "-0.5", "not_recorded", NA_character_),
  stringsAsFactors = FALSE
)
str(measurements)
  1. Inspect the input before changing it. The str() documentation describes a compact view of an object’s internal structure. For a data frame it can show the columns and abbreviated values. Here the raw measurement column should appear as character. Inspect your actual data with the same command before assuming the import produced that type.
  2. Convert into a new column. The numeric manual documents whitespace handling and NA with a warning for nonnumeric strings. The example therefore intentionally produces a coercion warning for not_recorded. Do not replace the raw column at this stage.
measurements$value = as.numeric(measurements$raw_value)
  1. Identify newly missing results. Compare missingness before and after conversion. This separates an already missing source entry from a result that became missing during conversion.
measurements$newly_missing =
  is.na(measurements$value) & !is.na(measurements$raw_value)
measurements
measurements[measurements$newly_missing, ]
  1. Resolve the flagged inputs using your data documentation. In this composite, inspect S04 and the token not_recorded. Decide from the study’s codebook whether it is a documented missing-value code, an export problem or something requiring correction. The flag identifies a conversion outcome; it does not supply that decision.

Save the conversion and the decision in the script that prepares the analysis data. For example, retain the original export and record which tokens were intentionally mapped to missingness. That is a workflow recommendation, rather than a rule imposed by as.numeric(). The guide to loading data into R provides the surrounding import context.

Output and how to read it

For the five illustrative rows, the converted values are 12.5, 8, -0.5, NA and NA in that order. The newly_missing flag is TRUE only for S04. S05 remains missing, but its source was already NA_character_, so it is not a newly missing conversion result. This distinction prevents an existing absence from being counted as a newly introduced problem.

The R missing-values manual explains that is.na() returns an elementwise logical result. It also treats NaN as missing. Consequently, this flag should be read as “missing after conversion despite a nonmissing input,” rather than “definitely malformed text.” For example, accepted special-value strings can also produce missing numeric results. Compare the retained input before assigning a reason.

Inspect the converted data frame again with str(measurements). The str() manual describes its display of structure, type or class, length and abbreviated contents, with attributes shown by default. It is a diagnostic display, not a replacement data frame returned for assignment. Read the display alongside the explicit row listing; abbreviated output is useful for orientation but should not substitute for inspecting a flagged value in full.

The Double-Precision Vectors manual adds a separate caution: conversion strips attributes, including names. Keep identifiers in their own data-frame column instead of relying on a vector’s names to carry the sample mapping through conversion. The same manual explains that double precision is finite; a numeric result is not a guarantee of exact preservation of arbitrarily long digit strings.

Troubleshooting

NAs introduced by coercion

Unrecognised text is a documented cause of NA results and a warning. Use the row-level flag above to locate affected inputs before revising the analysis. Do not automatically delete every flagged row: the meaning of a token belongs to the data documentation, while the warning describes a conversion problem.

The literal text “NA” and NA_character_ are different inputs, as the missing-values manual explains. A retained text column lets you distinguish them before conversion. If the export defines specific missing-value strings, handle them explicitly during import with na.strings rather than treating every unexpected token as an approved missing code.

Numbers containing decimal commas

Use an importer configured for the file’s convention. The Data Input documentation distinguishes read.csv(), which uses a comma field separator and decimal point, from read.csv2(), which uses a semicolon separator and decimal comma. For a small illustrative text input:

comma_data = read.csv2(text = "sample;value\nS01;12,5\nS02;8,0")
str(comma_data)

The point is to set the parsing convention at the boundary. Avoid deleting punctuation indiscriminately: that would be a separate data transformation requiring a documented interpretation. For a vector rather than a file, type.convert() offers a dec argument, but its type-selection behaviour differs from forcing every element through as.numeric().

Preserve the source text during import

The Data Input manual provides colClasses for specifying column classes. When the goal is an explicit conversion audit, importing the relevant fields as character lets the script retain the representation received from the file. Here is another illustrative composite, with column types and a missing token declared at import:

raw_import = read.csv(
  text = "sample_id,raw_value\nS01,12.5\nS02,MISSING",
  colClasses = "character",
  na.strings = "MISSING"
)
str(raw_import)

In this example, MISSING is an intentionally declared missing token. That choice precedes the numeric conversion, so the later newly_missing flag should not count it as a conversion failure. In a real file, replace that token only with one established by the export specification or codebook. Declaring a token in code records a decision; it does not establish that the decision was justified. Keep the original file when the exact token itself matters for audit.

A factor gives plausible but incorrect numbers

A factor stores codes associated with its levels. Direct numeric conversion retrieves those codes, rather than reading numeric labels as measurements. The official numeric example converts through character first: as.numeric(as.character(f)). Apply that pattern only when the labels themselves genuinely represent quantities; converting treatment names into numbers does not create a quantitative measurement.

This is a different problem from a warning: a code can look numerically valid while representing the wrong thing. Inspect the original labels before trusting the result. Keep categorical groups categorical when that is their meaning in the study.

The type is correct but the values still need review

Separate three checks in your analysis notes: whether the object has the intended type, whether conversion created missing results, and whether each remaining value has the intended meaning. A type inspection addresses the first; the audit flag addresses part of the second. Neither establishes units, allowable ranges or whether a digit string is an identifier.

For identifiers such as a sample barcode, preserving text can be the appropriate editorial choice. For quantities, compare selected original and converted rows before downstream calculations. In this composite, the proposed acceptance check is specific: S01 to S03 retain their intended numeric values, S04 is investigated, and S05 stays missing. It is not a general acceptance threshold for research data.

Free alternatives

These alternatives are functions supplied with R, which the R Project distributes as free software. They solve different tasks; the table is not a ranking. Each row refers to the official documentation named in Sources. Choose the operation according to whether you need explicit conversion, type inference or file parsing.

Function Documented role Difference to keep in mind
as.double(x) Converts an object to double precision. Identical to as.numeric(); it does not avoid the factor-code issue.
type.convert(x, as.is = TRUE) Selects a type accepting the nonmissing values. Can retain character data when the whole vector cannot be converted.
read.csv2(file) Reads a semicolon-separated table with decimal commas. Parses a file into a data frame rather than converting a single existing vector.

The type.convert() manual describes trying logical, integer, numeric and complex representations and choosing the first compatible type. Its na.strings argument identifies missing tokens; as.is controls retaining strings as character; dec sets the decimal character. The numerals argument can warn about or prevent conversions that lose precision. Specify these deliberately instead of expecting type inference to express the study’s variable definitions.

For example, type.convert(c(“12.5”, “not_recorded”), as.is = TRUE) retains text, whereas the forced conversion in the walkthrough gives a numeric result containing a missing entry. Both behaviours can be useful, but they answer different preparation tasks. Once the conversion policy is settled, keep it beside the remaining data-frame preparation steps in R so that later analysis does not silently change it.

Sources

Data: R numeric conversion situations and audit checks

Original compilation across R Core Team manuals, contrasting explicit conversion, factor encoding, missing-value detection and import-time parsing. These are documented behaviours and editorial audit checks, not observed research measurements.

R numeric conversion situations and audit checks
Input situationDocumented behaviourAudit checkPrimary documentation
Plain numeric textas.numeric converts text to a numeric vector.Retain the raw input alongside converted values.https://stat.ethz.ch/R-manual/R-devel/library/base/html/numeric.html
Unrecognised text tokenNonnumeric strings produce NA with a warning.Compare source and output missingness; investigate the token.https://stat.ethz.ch/R-manual/R-devel/library/base/html/numeric.html
Factor with numeric labelsDirect conversion returns underlying level codes.Inspect labels; use character conversion first if labels are quantities.https://stat.ethz.ch/R-manual/R-devel/library/base/html/factor.html
Already missing inputNA can be coerced to numeric; is.na detects missing entries.Separate pre-existing missingness from newly missing results.https://stat.ethz.ch/R-manual/R-devel/library/base/html/NA.html
Named ordinary vectorDouble conversion strips attributes, including names.Keep row identifiers separately from vector names.https://stat.ethz.ch/R-manual/R-devel/library/base/html/double.html
Mixed numeric and other texttype.convert selects the first type accepting all nonmissing values.Set as.is explicitly; inspect whether text was retained.https://stat.ethz.ch/R-manual/R-devel/library/utils/html/type.convert.html
Semicolon file with decimal commasread.csv2 defaults to a semicolon separator and decimal comma.Configure the importer to match the file convention.https://stat.ethz.ch/R-manual/R-devel/library/utils/html/read.table.html

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about as.numeric in R: Safe Numeric Conversion

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →