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

Matt Bannert picture Matt Bannert · Feb 13, 2012 · Viewed 14.8k times · Source

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.

Answer

Bernd Elkemann picture Bernd Elkemann · Feb 13, 2012

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