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\"
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 "
Add a minus in front of the 8 to get a left-aligned padded string