Reputation: 19883
I would like to paste
two character strings together and pad at the end with another character to make the combination a certain length. I was wondering if there was an option to paste
that one can pass or another trick that I am missing? I can do this in multiple lines by figuring out the length of each and then calling paste
with rep(my_pad_character,N)
but I would like to do this in one line.
Ex: pad together "hi"
, and "hello"
and pad with an "a"
to make the sequence length 10. the result would be "hihelloaaa"
Upvotes: 4
Views: 293
Reputation: 174948
Here is one option:
s1 <- "hi"
s2 <- "hello"
f <- function(x, y, pad = "a", length = 10) {
out <- paste0(x, y)
nc <- nchar(out)
paste0(out, paste(rep(pad, length - nc), collapse = ""))
}
> f(s1, s2)
[1] "hihelloaaa"
Upvotes: 8
Reputation: 115505
You can use the stringr
function str_pad
library(stringr)
str_pad(paste0('hi','hello'), side = 'right', width = 10 , pad = 'a')
Upvotes: 5