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.
sprintf() function in R Language uses Format provided by the user to return the formatted string with the use of the values in the list. Syntax: sprintf(format, values) Parameter: format: Format of printing the values.
sprintf() in C sprintf stands for "string print". In C programming language, it is a file handling function that is used to send formatted output to the string. Instead of printing on console, sprintf() function stores the output on char buffer that is specified in sprintf.
How to print Non-Numeric Values with sprintf() in R. To print the Non-Numeric Values in R, use the sprintf() method. You can also combine numeric values with non-numeric inputs.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With