20

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.

Bernd Elkemann
  • 23,242
  • 4
  • 37
  • 66
Matt Bannert
  • 27,631
  • 38
  • 141
  • 207

3 Answers3

25

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

Bernd Elkemann
  • 23,242
  • 4
  • 37
  • 66
12

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.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
  • Is there a direct way to add trailing `0`s instead of whitespaces using `sprintf()`? I am currently wrapping the outcome in `gsub(" ", "0", ...)`, which feels a bit cumbersome. – fdetsch Jan 20 '21 at 14:07
1

The stringr package provides str_pad:

library(stringr)
x <- c("fjdlksa01dada","rau","sjklf")
str_pad(x, width=8, side="right")

which yields:

[1] "fjdlksa01dada" "rau     "      "sjklf   "
Ryan C. Thompson
  • 40,856
  • 28
  • 97
  • 159