R Program to Add Leading Zeros to Vector

Example 1: Using paste0() to add Leading Zeros to R Vectors

employee_id <- c(11, 12, 13, 14)

# add leading zeros
result <- paste0("0", employee_id)

print(result) 

Output

[1] "011" "012" "013" "014"

In the above example, we have used the paste0() function to add zero at the beginning of each vector element.

paste0("0", employee_id)

Here, inside paste0() we have passed,

  • "0" - number of leading zeros we want to add
  • employee_id - the name of the vector

Example 2: Using sprintf() to add Leading Zeros to R Vectors

employee_id <- c(11, 12, 13, 14)

# add leading zeros
sprintf("%004d", employee_id)

Output

[1] "0011" "0012" "0013" "0014"

Here, we have passed the sprintf() function to add 2 zeros at the beginning of each vector element.

The formatting code %004d inside sprintf() means add 2 leading zeros and format vector elements as an integer of width 4.