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.
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")
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