0 votes
1 view
in R Programming by (6.5k points)

I have a set of data which looks something like this:

anim <- c(25499,25500,25501,25502,25503,25504)

sex  <- c(1,2,2,1,2,1)

wt   <- c(0.8,1.2,1.0,2.0,1.8,1.4)

data <- data.frame(anim,sex,wt)

data

   anim sex  wt anim2

1 25499   1 0.8     2

2 25500   2 1.2     2

3 25501   2 1.0     2

4 25502   1 2.0     2

5 25503   2 1.8     2

6 25504   1 1.4     2

I would like a zero to be added before each animal id:

data

   anim sex  wt anim2

1 025499   1 0.8     2

2 025500   2 1.2     2

3 025501   2 1.0     2

4 025502   1 2.0     2

5 025503   2 1.8     2

6 025504   1 1.4     2

And for interest sake, what if I need to add two or three zeros before the animal id's?

1 Answer

0 votes
by (25.3k points)

To add leading zeros to values in a column, you can use the paste() function as follows:

data$anim <-paste("0", data$anim, sep = "")

Output:

    anim sex  wt

1 025499   1 0.8

2 025500   2 1.2

3 025501   2 1.0

4 025502   1 2.0

5 025503   2 1.8

6 025504   1 1.4

Alternatively, you can also use the sprint() function regardless of how many digits are in the column.

For the same example above:

data$anim <- sprintf("%06d", data$anim)

Output: 

      anim sex  wt

1 025499   1 0.8

2 025500   2 1.2

3 025501   2 1.0

4 025502   1 2.0

5 025503   2 1.8

6 025504   1 1.4

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...