adding a variable length padding to each element in a string/character vector

Viewed 417

I'm not very knowledgeable in R but know a reasonable amount about a few other languages and have a solution to this but I want to know if there is a more efficient way as I plan to use this for large lists. I've looked online a few times and tired various things with no luck, this answer may be the answer but I cant seem to make it work.

I have a list of strings from an external file, each potentially with a different number of characters in each element. I would like to pad this list (with trailing white space) so that all elements have the same length. I’ll use ‘+‘ in place of white space in the example for clarify. So

c(“dog”, “cat”, “mouse”, “hare”, “snake”) 

would become

[1] “dog++”, “cat++", “mouse”, “hare+”, “snake”

What I have works but I think there will be a more efficient and elegant solution using paste, rep or similar. Y is my character list

# find max length of elements 
maxY <- max(nchar(Y))

# size of padding to each element
Ydif <- max(nchar(Y)) - nchar(Y) 

# pad each string element with the required amount of white space
for (l in 1:length(Ydif)) {
  if (Ydif[l] > 0) {
    Ypad[l] = strrep(" ", times=Ydif[l])
  } else {
      Ypad[l] = "" # if zero dont add padding
   }
}

# combine the padding with the original list to get all the same length
paste0(Y,Ypad, collapse=NULL)
3 Answers

One stringr option could be:

str_pad(x, max(nchar(x)), pad = "+", side = "right")

[1] "dog++" "cat++" "mouse" "hare+" "snake"

A base R solution, that splits the strings, adjusts the lengths and paste0s together after replaceing NAs with "+".

o <- lapply(strsplit(x, ""), `length<-`, max(nchar(x)))
o <- sapply(o, function(o) Reduce(paste0, replace(o, is.na(o), "+")))
o
# [1] "dog++" "cat++" "mouse" "hare+" "snake"

(Sidenote: Unfortunately strtrim(x, max(nchar(x)), fill="+") doesn't work, would be a great feature though.)


Data:

x <- c("dog", "cat", "mouse", "hare", "snake") 

A vectorised base R option :

vec <- c("dog", "cat", "mouse", "hare", "snake") 
n <- max(nchar(vec))
paste0(vec, strrep('+', n - nchar(vec)))
#[1] "dog++" "cat++" "mouse" "hare+" "snake"
Related