I am trying to write functions in R where the aim is to read multiple .csv files. They are named as 001.csv, 002.csv, ... 332.csv.
With paste
I managed to construct names 1.csv, 2.csv and so on, but I'm having difficulty with adding leading zeroes. There's a hint that the construction like sprintf("%03d", 7)
is required, but I have no idea why and how this works.
So can somebody explain what the following statement can actually does?
sprintf() in C sprintf stands for "string print". In C programming language, it is a file handling function that is used to send formatted output to the string. Instead of printing on console, sprintf() function stores the output on char buffer that is specified in sprintf.
"%03d" is a formatting string, which specifies how 7 will be printed. d stands for decimal integer (not double !), so it says there will be no floating point or anything like that, just a regular integer.
The printf function formats and writes output to the standard output stream, stdout . The sprintf function formats and stores a series of characters and values in the array pointed to by buffer. Any argument list is converted and put out according to the corresponding format specification in format.
sprintf
originally comes from C and all formatting rules are taken from it as well. See ?sprintf
in R or this or this reference to learn the subject in detail. Here I'll briefly outline what's the magic behind it.
"%03d"
is a formatting string, which specifies how 7
will be printed.
d
stands for decimal integer
(not double
!), so it says there will be no floating point or anything like that, just a regular integer.3
shows how many digits will the printed number have. More precisely, the number will take at least 3 digits: 7
will be __7
(with spaces instead of underscores), but 1000
will remain 1000
, as there is no way to write this number with just 3 digits.0
before 3
shows that leading spaces should be replaced by zeroes. Try experimenting with sprintf("%+3d", 7)
, sprintf("%-3d", 7)
to see other possible modifiers (they are called flags).That being said, the output from sprintf("%03d", 7)
will be 007
.
03d will print minimum 3 digit output...if then the output is less than 3 digit it will add zeros in beginning.If output is more than single 3 digits it will simply print output. if output(%d)= 2, with %3d will will be printed as = 002
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With