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!
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.
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.