Rich Scriven Rich Scriven - 2 months ago 6
R Question

Programmatically insert string width value into sprintf()

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()
?

Answer

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               "