Separating currencies from a string

39 Views Asked by At

I would like to have to separate columns from this data frame one for price value the other one for currency using R regular expression. I have tried

df = 50, 000 USD, 40,000 EUR, 8,500 GBP
df %>% 
  select(price) %>%
  mutate(priceValue = str_replace(price, "\\w+$", ""),
1

There are 1 best solutions below

1
HoelR On

Your sample

# A tibble: 3 × 1
  price     
  <chr>     
1 50,000 USD
2 40,000 EUR
3 8,500 GBP 

df %>% 
  mutate(
    currency = str_remove_all(price, "(?s:.*)\\s"),
    price = str_remove_all(price, "[^0-9]") %>% 
            as.numeric()
  )

# A tibble: 3 × 2
  price currency
  <dbl> <chr>   
1 50000 USD     
2 40000 EUR     
3  8500 GBP