R Program to Add Leading Zeros to Vector

[This article was first published on R feed, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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.

To leave a comment for the author, please follow the link and comment on their blog: R feed.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)