Skip to contents

Normalize the package's supported decimal and grouping separators, then coerce values to numeric. Use this helper for simple character columns whose separator convention is known; it is not a general locale or units parser.

Usage

toNumeric(x)

Arguments

x

An atomic vector or factor. Values are processed as character text and returned as a plain numeric vector of the same length.

Value

A numeric vector with one output per input value. Failed conversions are NA_real_; numeric NaN remains a missing numeric value.

Supported grammar

ASCII spaces are removed first. A value containing two or more period-plus- digits groups has every period removed; the analogous rule removes every comma from a value containing two or more comma-plus-digits groups. After those rules, one comma in a complete string of the form -?[0-9]+,[0-9]+ is changed to a decimal point. Base R numeric conversion handles the remaining text, including ordinary point decimals, scientific notation, and Inf.

Group widths are not validated. Thus "1.234.567" and "1,234,567" become 1234567, while "1,2,3" becomes 123. A single separator is interpreted as decimal: both "1.234" and "1,234" become 1.234.

Missing, ambiguous, and unit-bearing values

Missing inputs remain missing. Conversion warnings are suppressed and text outside the supported grammar becomes NA_real_; this includes mixed separators such as "1,234.56", currency symbols, and unit suffixes. Numbers are not scaled and units are not converted or preserved as metadata. Resolve ambiguous separators and harmonize units before calling this helper.

See also

which.nonnum() for positions that fail direct base R numeric conversion. buildDataset() applies toNumeric() to character columns and replaces a column only when all of its non-missing values convert.

Examples

x <- c("1 234", "1.234.567", "1,25", "1,234", "1,234.56", NA)
data.frame(input = x, numeric = toNumeric(x))
#>       input     numeric
#> 1     1 234    1234.000
#> 2 1.234.567 1234567.000
#> 3      1,25       1.250
#> 4     1,234       1.234
#> 5  1,234.56          NA
#> 6      <NA>          NA