Add Leading Zeros in R (Example)
This article shows how to add leading zeros to a vector in the R programming language.
Below, you can find a reproducible R code. The R code is structured as follows:
So without further ado, let’s dig in!
Example Data
In the example of this tutorial, I’ll use the following example data:
vec <- c(11111, 21212121, 333, 12345, 0) # Create example vector vec # Print vector to RStudio console # 11111 21212121 333 12345 0
As you can see based on the RStudio console output, the example data is a simple numeric vector with five elements
Addition of Leading Zeros in R
In order to add a leading zero to each of our vector elements, we can use the paste0 R function as follows:
vec_0 <- paste0("0", vec) # Add leading zeros vec_0 # Print updated vector # "011111" "021212121" "0333" "012345" "00"
Compare the updated vector with our original data. We added a zero to each element of our example vector.
Note: Our original data had the data object class numeric. After the addition of a zero at the beginning of each vector element, however, our vector was converted to the character class. We had to do this because R automatically removes all leading zeros for numeric data objects.
Further Resources
Do you need further explanations for the addition of leading zeros to a vector or a data frame column? Then you could have a look at the following video of my YouTube channel:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
In addition, you could also have a look at the other R tutorials on statisticsglobe.com:
In summary: I hope you learned in this tutorial how to add leading zeros in the R programming language. In case you have any further comments or questions, don’t hesitate to let me know in the comments section below.
Statistics Globe Newsletter
2 Comments. Leave new
Besides paste0, there is a function called str_pad, in the stringr package, which can add the leading zeroes. This function is also very efficient.
Hi John,
Thanks for sharing this additional alternative!
I just had a look at the str_pad function and came up with the following example code:
Seems to be a very interesting function, especially in case you want to create a character string with a fixed width.
Thanks again for sharing!
Joachim