2
votes

I have a string vector:

vec<-c("0","[0.046-0.112)","[0.112-0.141)","[0.141-0.177)","[0.177-0.206)",">=0.206")

I'd like to transform the decimal numbers inside this character vector in percent numbers. I usually use the package stingr to elab text with regex. So my idea is a thing like:

str_replace_all(vec, "([0-9.]{5})", paste(as.numeric("\\1")*100,"%") )

this is what I'd like to expect:

"0%" "[4.6%-11.2%)" "[11.2%-14.1%)" "[14.1%-17.7%)" "[17.7%-20.6%)" ">20.6%"   

but this is my output

[1] "0"           "[NA %-NA %)" "[NA %-NA %)" "[NA %-NA %)" "[NA %-NA %)"
[6] ">=NA %"     
Warning message:
In paste(round(as.numeric("\\1") * 100, 1), "%") :
  NAs introduced by coercion
1

1 Answers

4
votes

You can try

library(gsubfn)
gsubfn('[0-9.]+', ~ paste0(100*as.numeric(x), '%'), vec)
#[1] "0%"            "[4.6%-11.2%)"  "[11.2%-14.1%)" "[14.1%-17.7%)"
#[5] "[17.7%-20.6%)" ">=20.6%"