numextract: Extract Numeric Values from Character Strings

Description Usage Arguments Details Value Author(s) Examples

Description

Given a character string, this function will attempt to extract digits and return the result as a numeric value.

Usage

1
numextract(string, sequence = "first")

Arguments

string

A single string of class string to parse for digits.

sequence

A second character string, matching one of the following: "first", "last", "collapse", or "midpoint".

Details

All functions used are available in base R; no additional packages are required. If one matching sequence is identified, but the sequence argument is "midpoint" or "collapse", the function attempts to return a "safe" value. In this case, the only numeric match is returned. If no matches are found, the function returns numeric().

Value

Numeric value(s) occurring in string, or the midpoint of the first and last digits within the string.

Author(s)

Ryan Kyle, ryan.kyle@mail.mcgill.ca

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
example_string1 <- "12-15 HOURS"
example_string2 <- "DAY -1"

# Returns 12.
numextract(example_string1)
numextract(example_string1, sequence="first")

# Returns -15, a negative numeric value.
numextract(example_string1, sequence="last")

# Returns 1215, compressing two sequences into one.
numextract(example_string1, sequence="collapse")

# Returns 13.5, which is the midpoint of 15 and 12
(assumes second sequence does not correspond to negative numeric value).
numextract(example_string1, sequence="midpoint")

# All return -1
numextract(example_string2)
numextract(example_string2, sequence="first")
numextract(example_string2, sequence="last")
numextract(example_string2, sequence="midpoint")
numextract(example_string2, sequence="collapse")

rpkyle/cscmisc documentation built on May 13, 2019, 12:06 p.m.