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

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


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


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.


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   "