Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to paste two vectors together and pad at the end?

Tags:

string

r

paste

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"

like image 291
Alex Avatar asked Dec 11 '22 21:12

Alex


1 Answers

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"
like image 52
Gavin Simpson Avatar answered Jan 15 '23 14:01

Gavin Simpson