4

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

0

1 Answer 1

11

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               "
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.