Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace divided by symbol in numeric column

Tags:

r

dplyr

tidyverse

I have a data frame with following contents:

df$old_price <- c('SR 2356' , 'SR 785' , 'SR 50/4 pack', 'SR 10/4 pack,'SR 490')

How do I replace values in old_price column where values such 'SR 50/4 pack' or 'SR 10/4 pack to give out 12.5 and 2.5 respectively without corrupting the data?

I tried df$old_price <- as.integer(gsub('[a-zA-Z]', '', df$old_price)). However, it seems like it creates strange column values.

enter image description here

like image 605
Vikram Avatar asked Aug 07 '26 06:08

Vikram


1 Answers

This could be another solution:

library(stringr)

unlist(lapply(str_extract(vec, "\\d.*\\d"), \(x) eval(parse(text = x))))

[1] 2356.0  785.0   12.5    2.5  490.0

An alternative regex solution to suggested by dear Ian Campbell:

unlist(lapply(str_extract(vec, "[\\d,./]+"), \(x) eval(parse(text = x))))
like image 59
Anoushiravan R Avatar answered Aug 08 '26 18:08

Anoushiravan R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!