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)
question from:
https://stackoverflow.com/questions/65842619/adding-a-variable-length-padding-to-each-element-in-a-string-character-vector 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…