Here are the ways to add leading zeros to a vector in R:
- Using paste0()
- Using sprintf()
- Using str_pad()
Method 1: 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()
# 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:
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.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.