Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gsub and pad inside of a parenthesis

Tags:

r

I have vector like this:

x <- c("20(0.23)", "15(0.2)", "16(0.09)")

and I don't want to mess with the numbers on the outside of the parenthesis but want to remove the leading zero on the numbers inside and make everything have 2 digits. The output will look like:

"20(.23)", "15(.20)", "16(.09)"

Useful information:

I can remove leading zero and retain 2 digits using the function below taken from: LINK

numformat <- function(val) { sub("^(-?)0.", "\\1.", sprintf("%.2f", val)) }

numformat(c(0.2, 0.26))
#[1] ".20" ".26"

I know gsub can be used but I don't know how. I'll provide a strsplit answer but that's hackish at best.

like image 517
Tyler Rinker Avatar asked Oct 13 '12 20:10

Tyler Rinker


2 Answers

The gsubfn package allows you to replace anything matched by a regex with a function applied to the match. So we could use what you have with your numformat function

library(gsubfn)
# Note that I added as.numeric in because what will be passed in
# is a character string
numformat <- function(val){sub("^(-?)0.", "\\1.", sprintf("%.2f", as.numeric(val)))}
gsubfn("0\\.\\d+", numformat, x)
#[1] "20(.23)" "15(.20)" "16(.09)"
like image 127
Dason Avatar answered Nov 09 '22 03:11

Dason


pad.fix<-function(x){
y<-gsub('\\.(\\d)\\)','\\.\\10\\)',x)
gsub('0\\.','\\.',y)
}

the first gsub adds a trailing zero if needed the second gsub removes the leading zero.

like image 3
user1609452 Avatar answered Nov 09 '22 02:11

user1609452