Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...