How to Add Leading Zeros to Vector in R

Here are the ways to add leading zeros to a vector in R:

  1. Using paste0()
  2. Using sprintf()
  3. Using str_pad()

Method 1: Using paste0()

Visual representation of using paste0()

student_id <- c(11, 19, 21, 46)

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

print(result)

Output

[1] "011" "019" "021" "046"

Method 2: Using sprintf()

Visual representation of using sprintf()

# Define the number
number <- 21

# Specify the total number of digits (including leading zeros)
total_digits <- 5

# Add leading zeros using sprintf
formatted_number <- sprintf("%0*d", total_digits, number)

# Print the formatted number
print(formatted_number)

Output

[1] "00021"

Method 3: Using str_pad()

To use the str_pad() function, you need to install the stringr package and import it into your file.

Here is the figure and code:

Visual representation of using str_pad()

library(stringr)

# Define the number
number <- 21

# Specify the total number of digits (including leading zeros)
total_digits <- 5

# Add leading zeros using sprintf
formatted_number <- str_pad(number, width = total_digits, pad = "0")

# Print the formatted number
print(formatted_number)

Output

[1] "00021"

You can use both methods on a vector of numbers by using the same functions in a vectorized manner.

Leave a Comment