Skip to contents

If you have a string that contains characters and numbers, extract_numeric will extract the numeric parts. Anything between the numerics in the string will result in a separate element in the output.

Usage

extract_numeric(x, as_list = FALSE)

Arguments

x

A character vector.

as_list

Logical. Whether to return a list. See Details.

Value

A vector or list of numerics

Details

If a vector of strings is passed and you want to return something of the same length, set delist = FALSE and a list will be returned with the same length as the input vector.

Examples

extract_numeric("3h")
#> [1] 3

# With decimals
extract_numeric("3h 4h 5.5h")
#> [1] 3.0 4.0 5.5

# With negative values
extract_numeric("-2s4s 6s")
#> [1] -2  4  6

# With a vector of values
extract_numeric(c("2h", "3h", "7h"))
#> [1] 2 3 7
extract_numeric(c("2h", "3h 4h 5h 6h", "7h"))
#> [1] 2 3 4 5 6 7

# Return a list of the same length as the vector
extract_numeric(c("2h", "3h 4h 5h 6h", "7h"), as_list = TRUE)
#> [[1]]
#> [1] 2
#> 
#> [[2]]
#> [1] 3 4 5 6
#> 
#> [[3]]
#> [1] 7
#>