Sara Nicholson
Sara Nicholson

Reputation: 11

How to add 0s to middle of strings in a vector with R?

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.

Upvotes: 0

Views: 43

Answers (1)

akrun
akrun

Reputation: 886938

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"
)

Upvotes: 2

Related Questions