Matt Bannert
Matt Bannert

Reputation: 28264

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

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.

Upvotes: 20

Views: 16614

Answers (3)

Ryan C. Thompson
Ryan C. Thompson

Reputation: 42010

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   "

Upvotes: 1

Dirk is no longer here
Dirk is no longer here

Reputation: 368201

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.

Upvotes: 12

Bernd Elkemann
Bernd Elkemann

Reputation: 23550

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

Upvotes: 25

Related Questions