Create an integer column in an R data frame with leading zeros

R ProgrammingServer Side ProgrammingProgramming

To create an integer column in an R data frame with leading zeros, we can use sprintf function.

For Example, if we want to create a data frame column having values starting from 1 to 10 and we want to have 1 as 01 and so on then we can use the command given below −

data.frame(x=sprintf('%0.2d',1:10))

Check out the Examples given below to understand how it works.

Example 1

To create an integer column in an R data frame with leading zeros, use the command given below −

df1<-data.frame(x=sprintf('%0.3d',1:20))
df1

Output

If you execute the above given command, it generates the following Output −

    x
1  001
2  002
3  003
4  004
5  005
6  006
7  007
8  008
9  009
10 010
11 011
12 012
13 013
14 014
15 015
16 016
17 017
18 018
19 019
20 020

Example 2

To create an integer column in an R data frame with leading zeros, use the command given below −

df2<-data.frame(x=sprintf('%0.3d',sample(1:5,20,replace=TRUE)))
df2

Output

If you execute the above given command, it generates the following Output −

    x
1  002
2  002
3  002
4  001
5  005
6  005
7  004
8  004
9  001
10 004
11 005
12 002
13 004
14 003
15 003
16 002
17 001
18 002
19 004
20 005

Example 3

To create an integer column in an R data frame with leading zeros, use the command given below −

df3<-data.frame(x=sprintf('%0.3d',sample(1:100,20)))
df3

Output

If you execute the above given command, it generates the following Output −

    x
1  003
2  066
3  100
4  038
5  088
6  077
7  047
8  021
9  028
10 067
11 017
12 063
13 079
14 044
15 075
16 097
17 051
18 086
19 082
20 008
raja
Published on 03-Nov-2021 08:28:24
Advertisements