How to extract the value inside the first parenthesis of a string and add it to another new column

Viewed 70

I have a dataframe (df) with a column (Quantity) containing strings.

An extract of that column is shown below:

RoomType      Quantity

Comfort        Select rooms 0 1 (MUR 7,278) 2 (MUR 14,556) 3 (MUR 21,834) 4 (MUR 29,112) 5 (MUR 36,390) 6 (MUR 43,668) 7 (MUR 50,946) 8 (MUR 58,224) 9 (MUR 65,502) 10 (MUR 72,780)
Superior       Select rooms 0 1 (MUR 8,166) 2 (MUR 16,331) 3 (MUR 24,497) 4 (MUR 32,662) 5 (MUR 40,828) 6 (MUR 48,993) 7 (MUR 57,159) 8 (MUR 65,324) 9 (MUR 73,490) 10 (MUR 81,655)
...

I need to extract only the numbers inside the first parenthesis of each record in the dataframe and add them to a new column (say, DiscountedPrice).

I guess I need to use regex here but after doing some search online, I still can't figure out how to extract those values.

My R codes stand as follows:

library(dplyr)
library(stringr)

df %>% 
 mutate(DiscountedPrice = as.numeric(................) 

Expected output:

RoomType        Quantity     DiscountedPrice

Comfort        (as above)      7278
Superior       (as above)      8166

Any help would be much appreciated.

1 Answers

You can use -

df$DiscountedPrice <- as.numeric(gsub(',', '', 
                      sub('.*?\\(MUR (.*?)\\).*', '\\1', df$Quantity)))
df$DiscountedPrice
#[1] 7278 8166

pattern in sub ('.*?\\(MUR (.*?)\\).*') extracts the values after MUR until a closing bracket, gsub removes comma from the number and as.numeric will change the value to numeric.

data

df <- structure(list(RoomType = c("Comfort", "Superior"), Quantity = c("Select rooms 0 1 (MUR 7,278) 2 (MUR 14,556) 3 (MUR 21,834) 4 (MUR 29,112) 5 (MUR 36,390) 6 (MUR 43,668) 7 (MUR 50,946) 8 (MUR 58,224) 9 (MUR 65,502) 10 (MUR 72,780)", 
"Select rooms 0 1 (MUR 8,166) 2 (MUR 16,331) 3 (MUR 24,497) 4 (MUR 32,662) 5 (MUR 40,828) 6 (MUR 48,993) 7 (MUR 57,159) 8 (MUR 65,324) 9 (MUR 73,490) 10 (MUR 81,655)"
)), class = "data.frame", row.names = c(NA, -2L))
Related