Extracting Numbers from a String to Divide Them in R

I have a data frame where the last column looks like so:

Signed 1-yr/$2.5M deal with Pacers  
Signed 4-yr/$113M deal with Celtics 
Signed 3-yr/$30M deal with Pacers   
...

These are all strings. I am trying to get the number before -yr and the number before the M. So, for the first row, I am trying to get 2.5 and 1.

I then want to divide like so 2.5/1.

so the column would look like so:

2.5
28.25
10

I tried str_extract_all(df$col,"\\d") but this only gets the numbers into a list. I do not know of a way to accomplish my goal

>Solution :

A possible solution:

library(tidyverse)

df %>% 
  separate(V1, into = c("V2", "V3"), sep = "/", remove = F) %>% 
  mutate(result = parse_number(V3) / parse_number(V2)) %>% 
  select(V1, result)

#>                                     V1 result
#> 1 Signed 1-yr/$2.5M deal with Pacers     2.50
#> 2  Signed 4-yr/$113M deal with Celtics  28.25
#> 3 Signed 3-yr/$30M deal with Pacers     10.00

Leave a Reply