How to add zeros before numbers in R?


The easiest way to add zeros before numbers is by using paste0 function

Example

> ID <- c(25499,25500,25501,25502,25503,25504)
> Gender <- c(1,2,2,1,2,1)
> Lens <- c(0.8,1.2,1.0,2.0,1.8,1.4)
> data <- data.frame(ID,Gender,Lens)
> data
  ID Gender Lens
1 25499 1 0.8
2 25500 2 1.2
3 25501 2 1.0
4 25502 1 2.0
5 25503 2 1.8
6 25504 1 1.4

Let’s say we want to add 00 before every ID.

It can be done by using paste0 function as follows −

> IDs<-paste0("00",data$ID)
> newdata <- data.frame(IDs,Gender,Lens)
> newdata
IDs Gender Lens
1 0025499 1 0.8
2 0025500 2 1.2
3 0025501 2 1.0
4 0025502 1 2.0
5 0025503 2 1.8
6 0025504 1 1.4

Updated on: 06-Jul-2020

311 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements