cnumeric: Convert text to numbers

View source: R/all.R

cnumericR Documentation

Convert text to numbers

Description

This function takes characters that look like numbers and converts them to numbers. Its name is based on the VBA function CNumeric. It does some pre-processing before calling as.numeric.

  1. converts factors

  2. removes all whitespace

  3. converts wrapping "()" to negatives

  4. removes commas

  5. converts percentages to decimals

  6. calls as.numeric

Usage

cnumeric(v)

Arguments

v

a vector

Value

A vector of numerics. Returns NA when conversion is not possible after application of the rules above.

Examples

# Commas are removed
cnumeric(c('1,000,000', '2,000.03'))

# But, we don't check to make sure that
# commas are in the right place first
cnumeric(c('1,0,0', '2,0000.03'))

# Accounting-style negatives
cnumeric(c('(1,000.92)', '(4)'))

# Percents are converted
cnumeric(c('28.3%', '-1.3%', '(15%)'))

# If scientific notation is present, R knows what to do
cnumeric(c('3e7', '5e-1'))

# TODO it doesn't deal with currencies yet
cnumeric(c('USD 0.10', '$14.34'))


adamleerich/alrtools documentation built on March 12, 2024, 11:38 p.m.