0

I have a vector of sample names:

sample.names [1] "A10" "A13" "A15" "A16" "A17" "A18" "A19" "A20" "A21" "A23" "A24" "A5" "A6" "A7" [15] "A8" "C1" "C10" "C11" "C12" "C13" "C14" "C15" "C16" "C17" "C18" "C19" "C2" "C20" [29] "C21" "C22" "C23" "C24" "C3" "C4" "C6" "C7" "C8" "C9"

I need to add 0s before the single digits. I did this with the following command: paste(c(substr(i,1,1), substr(i,2,2)), collapse="0")

I do not understand how to replace those elements within my existing vector.... Here is my most recent attempt:

    if (nchar(i) < 3) {
    newi <- paste(c(substr(i,1,1), 
    substr(i,2,2)), collapse="0")
    replace(sample.names, i, newi)
      }
    }

I feel like this is a simple fix yet I have spent two hours trying to do this.

1 Answer 1

2

We may use sprintf with str_replace - match the digits (\\d+) in the pattern and replace with a function that converts the string to numeric, and then use sprintf with %02d inserts 0 whereever the number of digits is less than 2

library(stringr)
str_replace_all(sample.names, "\\d+",  function(x) sprintf("%02d", as.numeric(x)))

-output

[1] "A10" "A13" "A15" "A16" "A17" "A18" "A19" "A20" "A21" "A23" "A24" "A05" "A06" "A07" "A08" "C01" "C10" "C11" "C12" "C13" "C14" "C15" "C16" "C17" "C18"
[26] "C19" "C02" "C20" "C21" "C22" "C23" "C24" "C03" "C04" "C06" "C07" "C08" "C09"

data

sample.names <- c("A10", "A13", "A15", "A16", "A17", "A18", "A19", "A20", "A21", 
"A23", "A24", "A5", "A6", "A7", "A8", "C1", "C10", "C11", "C12", 
"C13", "C14", "C15", "C16", "C17", "C18", "C19", "C2", "C20", 
"C21", "C22", "C23", "C24", "C3", "C4", "C6", "C7", "C8", "C9"
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.