Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R regular expression replace :75% -> 0.75

Tags:

regex

r

Surely a naive question but I'm in R and I have the expression

v <- "gastrula:75%"

that I want to replace with "gastrula0.75"

I tried things like :

v <- sub("\\.(\\d+)%","0.\\1",v)
v <- sub("[:punct:](\\d)\\1+[:punct:]","0.\\1",v)

But I didn't find anything that worked.

like image 936
Erica Fary Avatar asked Jun 07 '26 07:06

Erica Fary


1 Answers

You may try

 sub('^([^:]+):(\\d+).*', '\\10.\\2', v)
 #[1] "gastrula0.75"

Or may be

 library(gsubfn)
 gsubfn(':(\\d+)%', ~as.numeric(x)/100, v)
 #[1] "gastrula0.75"

 v1 <- c(v, 'gastrula:5%')
 gsubfn(':(\\d+)%', ~as.numeric(x)/100, v1)
 #[1] "gastrula0.75" "gastrula0.05"
like image 107
akrun Avatar answered Jun 10 '26 03:06

akrun



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!