Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make all elemants of a character vector the same length

Tags:

string

r

Consider a character vector

test <- c('ab12','cd3','ef','gh03')

I need all elements of test to contain 4 characters (nchar(test[i])==4). If the actual length of the element is less than 4, the remaining places should be filled with zeroes. So, the result should look like this

> 'ab12','cd30','ef00','gh03'

My question is similar to this one. Yet, I need to work with a character vector.

like image 772
ikashnitsky Avatar asked Mar 21 '16 16:03

ikashnitsky


1 Answers

We can use base R functions to pad 0 at the end of a string to get the number of characters equal. The format with width specified as max of nchar (number of characters) of the vector gives an output with trailing space at the end (as format by default justify it to right. Then, we can replace each space with '0' using gsub. The pattern in the gsub is a single space (\\s) and the replacement is 0.

gsub("\\s", "0", format(test, width=max(nchar(test))))
#[1] "ab12" "cd30" "ef00" "gh03"

Or if we are using a package solution, then str_pad does this more easily as it also have the argument to specify the pad.

library(stringr)
str_pad(test, max(nchar(test)), side="right", pad="0")
like image 164
akrun Avatar answered Sep 23 '22 19:09

akrun