How to add leading zeros?
The short version: use formatC
or sprintf
.
The longer version:
There are several functions available for formatting numbers, including adding leading zeroes. Which one is best depends upon what other formatting you want to do.
The example from the question is quite easy since all the values have the same number of digits to begin with, so let's try a harder example of making powers of 10 width 8 too.
anim <- 25499:25504
x <- 10 ^ (0:5)
paste
(and it's variant paste0
) are often the first string manipulation functions that you come across. They aren't really designed for manipulating numbers, but they can be used for that. In the simple case where we always have to prepend a single zero, paste0
is the best solution.
paste0("0", anim)
## [1] "025499" "025500" "025501" "025502" "025503" "025504"
For the case where there are a variable number of digits in the numbers, you have to manually calculate how many zeroes to prepend, which is horrible enough that you should only do it out of morbid curiosity.
str_pad
from stringr
works similarly to paste
, making it more explicit that you want to pad things.
library(stringr)
str_pad(anim, 6, pad = "0")
## [1] "025499" "025500" "025501" "025502" "025503" "025504"
Again, it isn't really designed for use with numbers, so the harder case requires a little thinking about. We ought to just be able to say "pad with zeroes to width 8", but look at this output:
str_pad(x, 8, pad = "0")
## [1] "00000001" "00000010" "00000100" "00001000" "00010000" "0001e+05"
You need to set the scientific penalty option so that numbers are always formatted using fixed notation (rather than scientific notation).
library(withr)
with_options(
c(scipen = 999),
str_pad(x, 8, pad = "0")
)
## [1] "00000001" "00000010" "00000100" "00001000" "00010000" "00100000"
stri_pad
in stringi
works exactly like str_pad
from stringr
.
formatC
is an interface to the C function printf
. Using it requires some knowledge of the arcana of that underlying function (see link). In this case, the important points are the width
argument, format
being "d"
for "integer", and a "0"
flag
for prepending zeroes.
formatC(anim, width = 6, format = "d", flag = "0")
## [1] "025499" "025500" "025501" "025502" "025503" "025504"
formatC(x, width = 8, format = "d", flag = "0")
## [1] "00000001" "00000010" "00000100" "00001000" "00010000" "00100000"
This is my favourite solution, since it is easy to tinker with changing the width, and the function is powerful enough to make other formatting changes.
sprintf
is an interface to the C function of the same name; like formatC
but with a different syntax.
sprintf("%06d", anim)
## [1] "025499" "025500" "025501" "025502" "025503" "025504"
sprintf("%08d", x)
## [1] "00000001" "00000010" "00000100" "00001000" "00010000" "00100000"
The main advantage of sprintf
is that you can embed formatted numbers inside longer bits of text.
sprintf(
"Animal ID %06d was a %s.",
anim,
sample(c("lion", "tiger"), length(anim), replace = TRUE)
)
## [1] "Animal ID 025499 was a tiger." "Animal ID 025500 was a tiger."
## [3] "Animal ID 025501 was a lion." "Animal ID 025502 was a tiger."
## [5] "Animal ID 025503 was a tiger." "Animal ID 025504 was a lion."
See also goodside's answer.
For completeness it is worth mentioning the other formatting functions that are occasionally useful, but have no method of prepending zeroes.
format
, a generic function for formatting any kind of object, with a method for numbers. It works a little bit like formatC
, but with yet another interface.
prettyNum
is yet another formatting function, mostly for creating manual axis tick labels. It works particularly well for wide ranges of numbers.
The scales
package has several functions such as percent
, date_format
and dollar
for specialist format types.
Add leading Zero Python
You can use the builtin str.zfill
method, like this
my_string = "1"
print my_string.zfill(2) # Prints 01
my_string = "1000"
print my_string.zfill(2) # Prints 1000
From the docs,
Return the numeric string left filled with zeros in a string of length
width. A sign prefix is handled correctly. The original string is
returned if width is less than or equal to len(s).
So, if the actual string's length is more than the width specified (parameter passed to zfill
) the string is returned as it is.
How to add leading zeros to select rows in a data frame column using dplyr pipes
You can try this approach
data2 <- data %>%
mutate(ID = ifelse(row_number()<= 95, paste0("0", ID), ID))
head(data2)
# ID not.imp1 not.imp2 not.imp3
# 1 09449 -1.4297317 -2.2210106 0.1923912
# 2 07423 1.9010681 1.0825734 -0.8855694
# 3 06283 0.2508254 -0.5307967 2.1645044
# 4 05593 -2.2451267 0.1281156 -1.8528800
# 5 09194 -0.1677409 -0.7422480 -0.4237452
# 6 07270 -0.2536918 1.2289698 1.0083092
tail(data2)
# ID not.imp1 not.imp2 not.imp3
# 95 06538 1.0071791 0.1596557 -0.7099883
# 96 4829 0.2444440 0.8869954 -1.2938356
# 97 2571 -1.1012023 0.8343393 -0.6264487
# 98 150 0.2116460 -0.2146265 -1.8281045
# 99 3107 -1.2379193 0.3491078 1.4531531
# 100 9953 -0.9326725 1.1146032 -1.5542687
Add leading zeros to number string on informix SQL
I think you're looking for TO_CHAR()
with a numeric format string:
SELECT TO_CHAR(num_field, "&&&&&&&&&&&&&&") AS num_field_with_zeros
FROM the_table;
When I checked this, I used:
SELECT TO_CHAR(tabid, '&&&&&&&&&')
FROM "informix".systables
WHERE tabid > 100;
and got the output (in one particular database):
000000141
000000142
000000148
000000156
000000157
000000158
000000159
000000160
000000209
000000210
000000211
000000212
000000213
000000214
000000215
000000216
000000222
I simply chose to limit the output to 9 characters instead of 14.
How to add leading zeros to macro variable?
Use the Z format to generate numbers with leading zeros.
%do year=8 to 20;
%let year=%sysfunc(putn(&year,Z2.));
...
Related Topics
Stratified Random Sampling from Data Frame
Sum Rows in Data.Frame or Matrix
Create Counter Within Consecutive Runs of Certain Values
Can Lists Be Created That Name Themselves Based on Input Object Names
Create Grouping Variable For Consecutive Sequences and Split Vector
How to Find the Largest N Elements in a List in R
Removing Columns That Are All 0
Coerce Multiple Columns to Factors At Once
How to Write Ifelse Statement With Multiple Conditions in R
How to Change Y Axis Limits in Decimal Points in R
Select the First and Last Row by Group in a Data Frame
Generating All Distinct Permutations of a List in R
Categorize Numeric Variable into Group/ Bins/ Breaks
Looping Over a Date or Posixct Object Results in a Numeric Iterator