Explanation for sprintf functions ("% 03d", 7)?

I am trying to write functions in R where the goal is to read multiple CSV files. They are called 001.csv, 002.csv, ... 332.csv.

With paste I managed to create the names 1.csv, 2.csv, etc., but I had difficulty adding leading zeros. There is a hint that you want to build a construct like sprintf("%03d", 7) , but I have no idea why and how it works.

So can someone explain what the next statement can do?

+8
source share
1 answer

sprintf originally comes from C, and all formatting rules are also taken from it. See ?sprintf in R or this or this link to learn the subject in detail. Here I will briefly outline what magic is behind this.

"%03d" is a format string that determines how 7 will be printed.

  • d stands for decimal integer (not double !), so it says that there will be no floating point number or something like that, just a regular integer.
  • 3 shows how many digits the printed number will have. More precisely, the number will consist of at least 3 digits: 7 will be __7 (with spaces instead of underlining), but 1000 will remain 1000 , since it is impossible to write this number in just 3 digits.
  • 0 before 3 indicates that leading spaces should be replaced with zeros. Try experimenting with sprintf("%+3d", 7) , sprintf("%-3d", 7) to see other possible modifiers (they are called flags).

The output of sprintf("%03d", 7) will be 007 .

+24
source

Source: https://habr.com/ru/post/969451/


All Articles