text2decimal: Convert Mixed Text to Decimal

Description Usage Arguments Details Value Author(s) References Examples

Description

Convert character to numeric value where possible.

Usage

1

Arguments

x

character

Details

x is coerced to character. Leading/trailing text is dropped; and the result is coerced to numeric. Useful, e.g., where measurements are reported with units.

Leading text consists of characters not among 0:9, +,-, or .. The numeric region, if any, is the first consecutive string of those characters, and may also include e or E. Any remaining characters are considered trailing. Elements are substituted with their numeric regions, and the result is passed to as.numeric.

Changes were made as of version 5.9 to support scientific notation. Note that 'e3' and '3e' both give 3: the first has 'e' stripped before coercion, and the second is valid syntax (e.g., as.numeric('3e')). Due to a bugfix in version 5.15, "3X" (where X is a capital letter, or 'a','b','c','d') now returns 3 not NA.

Value

numeric

Author(s)

Tim Bergsma

References

http://metrumrg.googlecode.com

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
text2decimal('every 3.5 hours')
text2decimal('-17 units')
x <- c(
  'I have -0.3 apples.',
  'I have -3 apples.',
  'I have 3. apples.',
  'I have +3 apples.',
  '3',
  'I have 3',
  '3 apples.',
  'I have e3 apples.',
  'I have 3e apples.',
  'I have +.3 apples.',
  'I have .3 apples.',
  'I have 0.3 apples.',
  'I have 1e3 apples.',
  'I have -1e-3 apples.',
  'I have 1E3 apples.',
  'I have 30e10 apples.',
  'I have 30 + apples.',
  'I have 3G apples.',
  'I have 30+ apples.',
  'I have ++.3 apples.',
  'I have +e3 apples.',
  'I have .3.2 apples.',
  'I have no apples.'
)
suppressWarnings(data.frame(x=x,as.decimal=text2decimal(x))) # last 5 are NA

metrumrg documentation built on May 2, 2019, 5:55 p.m.