Learn R Programming

DescTools (version 0.99.19)

StrVal: Extract All Numeric Values From a String

Description

Extract all numeric values from a string, using a regular expression and return a list of the values. If there are several, the values can be either be pasted and/or casted from character vectors to numeric values.

Usage

StrVal(x, paste = FALSE, as.numeric = FALSE)

Arguments

x
a character vector

paste
should separatetly extracted numbers be pasted together? This can be useful to reverse a prior format action. Default is FALSE.
as.numeric
logical value, determining if the extracted values should be converted to a number or be returned as characters. Default is FALSE.

Value

Details

If there are multiple numbers in the same string to paste and cast to numeric, pasting will be done first and after pasting the conversion will be performed. So if for example the numbers in x = "34 way 066" should be extracted StrVal(x, paste = TRUE, as.numeric = TRUE) will lead to 34066.

See Also

other string functions, e.g. StrTrunc

Examples

Run this code
# a simple vector with only one number per element
StrVal(x=c("week 1", "week 3", "week 4", "week 5"))

# several numbers per element, extract each part, do not paste and return characters
StrVal(x=c("This is 1. place: 45.2", "none", "12.1 but -2.7 follow, 10.2e23 "),
       paste = FALSE, as.numeric = FALSE)

# a typical use case for this function is to reverse a previously
#   applied number format

x <- c(100000, 4564654632, -456463)
xf <- Format(x, big.mark="'")

StrVal(xf, paste = TRUE, as.numeric = TRUE)

StrVal(xf, paste = TRUE, as.numeric = FALSE)
StrVal(xf, paste = FALSE, as.numeric = TRUE)
StrVal(xf, paste = FALSE, as.numeric = FALSE)

Run the code above in your browser using DataLab