Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use R's sprintf to create fixed width strings with fill whitespace at the END?

Tags:

I have vector of strings and want to create a fixed with string out of that. Shorter strings should be filled up with white spaces. E.g.:

c("fjdlksa01dada","rau","sjklf")
sprintf("%8s")
# returns
[1] "fjdlksa01dada" "     rau"      "   sjklf"

But how can I get the additional whitespace at the END of the string?

Note that I heard of write.fwf from the gdata package which is really nice but doesn't help much in this case, because I need to write a very specific non-standard format for an outdated old program.

like image 303
Matt Bannert Avatar asked Feb 13 '12 14:02

Matt Bannert


People also ask

What is sprintf () in R?

sprintf() function in R Language uses Format provided by the user to return the formatted string with the use of the values in the list. Syntax: sprintf(format, values) Parameter: format: Format of printing the values.

What is sprintf () in C?

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.

How do I print Sprintf in R?

How to print Non-Numeric Values with sprintf() in R. To print the Non-Numeric Values in R, use the sprintf() method. You can also combine numeric values with non-numeric inputs.


2 Answers

Add a minus in front of the 8 to get a left-aligned padded string

like image 75
Bernd Elkemann Avatar answered Sep 17 '22 00:09

Bernd Elkemann


That is almost more of a standard "C" rather than R question as it pertains to printf format strings. You can even test this on a command-prompt:

edd@max:~$ printf "[% 8s]\n" foo
[     foo]
edd@max:~$ printf "[%-8s]\n" foo
[foo     ]
edd@max:~$ 

and in R it works the same for padding left:

R> vec <- c("fjdlksa01dada","rau","sjklf")
R> sprintf("% 8s", vec)
[1] "fjdlksa01dada" "     rau"      "   sjklf"     
R> 

and right

R> sprintf("%-8s", vec)
[1] "fjdlksa01dada" "rau     "      "sjklf   "     
R> 

Edit: Updated once I understood better what @ran2 actually asked for.

like image 36
Dirk Eddelbuettel Avatar answered Sep 19 '22 00:09

Dirk Eddelbuettel