I am trying to programmatically insert the string width value into a sprintf()
format.
The desired result is
sprintf("%-20s", "hello")
# [1] "hello "
But I want to insert the 20
on the fly, in the same call, so that it can be any number. I have tried
sprintf("%%-%ds", 20, "hello")
# [1] "%-20s"
sprintf("%-%ds", 20, "hello")
# Error in sprintf("%-%ds", 20, "hello") :
# invalid format '%-%d'; use format %f, %e, %g or %a for numeric objects
sprintf("%-%%ds", 20, "hello")
# Error in sprintf("%-%%ds", 20, "hello") :
# invalid format '%-%%d'; use format %f, %e, %g or %a for numeric objects
Is this possible in sprintf()
?
Yes, This is possible by using the asterisk *
.
As mentioned in the docs,
A field width or precision (but not both) may be indicated by an asterisk *: in this case an argument specifies the desired number
Hence the code would be
> sprintf("%-*s", 20, "hello")
[1] "hello "
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