2

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 Answer 1

4

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%"      
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.