The currency of a number is defined as the character coming before the number in the string. If nothing comes before (i.e. if the number is the first thing in the string), the currency is the empty string, similarly the currency can be a space, comma or any manner of thing.
str_extract_currencies(string)
str_nth_currency(string, n)
str_first_currency(string)
str_last_currency(string)
A data frame with 4 columns: string_num
, string
, curr_sym
and
amount
. Every extracted currency amount gets its own row in the data
frame detailing the string number and string that it was extracted from,
the currency symbol and the amount.
These functions are vectorized over string
and n
.
str_extract_currencies()
extracts all currency amounts.
str_nth_currency()
just gets the n
th currency amount from each string.
str_first_currency(string)
and str_last_currency(string)
are just
wrappers for str_nth_currency(string, n = 1)
and str_nth_currency(string, n = -1)
.
"-$2.00" and "$-2.00" are interpreted as negative two dollars.
If you request e.g. the 5th currency amount but there are only 3 currency
amounts, you get an amount and currency symbol of NA
.
string <- c("ab3 13", "$1", "35.00 $1.14", "abc5 $3.8", "stuff")
str_extract_currencies(string)
#> string_num string curr_sym amount
#> 1 1 ab3 13 b 3.00
#> 2 1 ab3 13 13.00
#> 3 2 $1 $ 1.00
#> 4 3 35.00 $1.14 35.00
#> 5 3 35.00 $1.14 $ 1.14
#> 6 4 abc5 $3.8 c 5.00
#> 7 4 abc5 $3.8 $ 3.80
str_nth_currency(string, n = 2)
#> string_num string curr_sym amount
#> 1 1 ab3 13 13.00
#> 2 2 $1 <NA> NA
#> 3 3 35.00 $1.14 $ 1.14
#> 4 4 abc5 $3.8 $ 3.80
#> 5 5 stuff <NA> NA
str_nth_currency(string, n = -2)
#> string_num string curr_sym amount
#> 1 1 ab3 13 b 3
#> 2 2 $1 <NA> NA
#> 3 3 35.00 $1.14 35
#> 4 4 abc5 $3.8 c 5
#> 5 5 stuff <NA> NA
str_nth_currency(string, c(1, -2, 1, 2, -1))
#> string_num string curr_sym amount
#> 1 1 ab3 13 b 3.0
#> 2 2 $1 <NA> NA
#> 3 3 35.00 $1.14 35.0
#> 4 4 abc5 $3.8 $ 3.8
#> 5 5 stuff <NA> NA
str_first_currency(string)
#> string_num string curr_sym amount
#> 1 1 ab3 13 b 3
#> 2 2 $1 $ 1
#> 3 3 35.00 $1.14 35
#> 4 4 abc5 $3.8 c 5
#> 5 5 stuff <NA> NA
str_last_currency(string)
#> string_num string curr_sym amount
#> 1 1 ab3 13 13.00
#> 2 2 $1 $ 1.00
#> 3 3 35.00 $1.14 $ 1.14
#> 4 4 abc5 $3.8 $ 3.80
#> 5 5 stuff <NA> NA