Bolivar Sotomayor
Bolivar Sotomayor

Reputation: 11

Replacing a number in a vector in R

I´m new at R i really appreciate if you could help me. I want to create a function that allows me to change the contents of a vector. The idea is: I introduce any vector, then if a number of the vector has 1 caracter, the number will transform in to a number with 3 caracters adding "00" in front of the number; if the number has 2 caracters, the function will add "0" and if the number has 3 caracters the number will be the same. strong text I have this function; it works whe the vector starts at 1; but if it starts with a different number, problems happens. Please forgive me if my english it´s not so good, and thanks.

a <- 1:10
f5 <- function(a){
    for(i in a){
        if (nchar(a[i])==1){
            a[i] <- paste("00",a[i],sep ="")
        }

        if (nchar(a[i])==2){
            a[i] <- paste("0",a[i],sep ="")
                }

    if (nchar(a[i])==3){
        a[i] <- paste(a[i],sep ="")

    }
    }
a
}

Upvotes: 1

Views: 137

Answers (1)

Zelazny7
Zelazny7

Reputation: 40648

Use the sprintf function which can add leading zeros:

# test vector
v <- 1:10
> cat(sprintf("%03d", v))
001 002 003 004 005 006 007 008 009 010

Just change the number in front of the "d" to change the number of leading zeros.

# More examples:
v2 <- c(1, 50, 999)
> cat(sprintf("%03d", v2))
001 050 999

You can actually change the elements, too, not just print them:

v2 <- c(1, 50, 999)
v3 <- sprintf("%03d", v2)
> v3
[1] "001" "050" "999"

> class(v3)
[1] "character"

And compare this method with naltipar's method:

> all.equal(sapply(v2, add.zeros), v3)
[1] TRUE

They're identical

Upvotes: 3

Related Questions