Add Leading Zeros to the Elements of a Vector in R Programming – Using paste0() and sprintf() Function

paste0() and sprintf() functions in R Language can also be used to add leading zeros to each element of a vector passed to it as argument.

Syntax:
paste0(“0”, vec)
or
sprintf(“%0d”, vec)

Parameters:
paste0: It will add zeros to vector
sprintf: To format a vector(adding zeros)
vec: Original vector data

Returns: Vectors by additon of leading zeros

Example 1:



filter_none

edit
close

play_arrow

link
brightness_4
code

# R Program to add leading zeros
  
# Create example vector
vec <- c(375, 21, 1, 7, 0) 
vec   
  
# Add leading zeros
vec_0 <- paste0("0", vec) 
vec_0      

chevron_right


Output :

[1] 375  21   1   7   0
[1] "0375" "021"  "01"   "07"   "00"  

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R Program to add leading zeros
  
# Create example vector
vec <- seq(5)
  
# Add leading zeros
sprintf("sequence_%03d", vec)

chevron_right


Output :

[1] "sequence_001" "sequence_002" "sequence_003" "sequence_004" "sequence_005"
My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.