-1

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+$", ""),
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 1
    What is `df`?... Please use `dput()` to share a reproducible example – Sotos Dec 28 '22 at 14:38
  • df is the dataframe with the price column (price=c(50, 000 USD, 40,000 EUR, 8,500 GBP) – Nick Vigman Dec 28 '22 at 14:41
  • Is that just one string? Like this? `structure(list(price = "50, 000 USD, 40,000 EUR, 8,500 GBP"), class = "data.frame", row.names = c(NA, -1L))` – Sotos Dec 28 '22 at 14:42

1 Answers1

0

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     
Chamkrai
  • 5,912
  • 1
  • 4
  • 14