Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading