I am reading data from a csv file and one of the columns in the data comes in three different formats:
xxxxx-xxx-xx (5-3-2)
xxxxx-xxxx-x (5-4-1)
xxxx-xxxx-xx (4-4-2)
My goal is to turn these three different styles into one style in the form: xxxxx-xxxx-xx (5-4-2)
In order to make all the different forms the same I need to insert an additional zero at the specific location on each of the 3 different conditions like so:
xxxxx-0xxx-xx
xxxxx-xxxx-0x
0xxxx-xxxx-xx
Anyone have thoughts on the best way to accomplish this?
I would do this using sprintf and strsplit:
x <- c('11111-111-11', '11111-1111-1', '1111-1111-11')
y <- strsplit(x, '-')
myfun <- function(y) {
first <- sprintf('%05d', as.integer(y[1]))
second <- sprintf('%04d', as.integer(y[2]))
third <- sprintf('%02d', as.integer(y[3]))
paste(first, second, third, sep='-')
}
sapply(y, myfun)
# [1] "11111-0111-11" "11111-1111-01" "01111-1111-11"
You could also do this with fancy regular expressions or the gsubfn package but that may be overkill!
Slightly shorter and a more functional programming version of Justin's solution
numbers <- c('11111-111-11', '11111-1111-1', '1111-1111-11')
restyle <- function(number, fmt){
tmp <- as.list(as.integer(strsplit(number, '-')[[1]]))
do.call(sprintf, modifyList(tmp, list(fmt = fmt)))
}
sapply(numbers, restyle, fmt = '%05d-%04d-%02d', USE.NAMES = F)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With